getJSON not returning anything
The JSON function below is not returning anything...
$.getJSON(formUrl, function(data) {
alert(data)
$('.response').html('<p>' + data.title + '</p>'
+ '<p>' + data.description + '</p>');
});
the formUrl is correct and returning data in the form of
{"title":"Smashing Magazine","description":"Smashing Magazine is focused on design and web-development. We deliver useful information, latest trends and techniques, useful ideas, innovative approaches and tools."}
Can someon开发者_C百科e point out what I'm doing wrong? I'm alerting the data and its empty as well...
Thanks!
Are you calling $.getJSON
with a cross-domain URL (ie. from localhost to somewhere else)? That won't work unless you use the JSONP dataType.
Since it's not of the same origin, you need to add the Access-Control
headers to the JSON response.
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
Do not break the string in two lines, it will result in error and may be the reason of Javascript not running.
Try something like this: (Notice how I did not break the content inside html() in two lines)
$.getJSON(formUrl, function(data) {
alert(data);
$('.response').html('<p>' + data.title + '</p>' + '<p>' + data.description + '</p>');
});
Try to configure your server to deliver the page fetch.php
with a contentType application/json
Also just for a test, you can try to put your JSON into a .../fetch.js
file and call it with $.getJSON
.
It should work, as .js files are application/javascript
by default on most servers.
精彩评论