I'm getting a bit of a headache trying to figure this one out. To request some json-data from a PHP-script via Ajax, I'm using the jQuery function:
$.ajax({
type: 'GET',
cache: 'false',
url: ajaxUrl,
data: dataString,
success: updatePage
});
If I don't set content-type in the PHP header to:
header('Content-type:开发者_StackOverflow社区 application/json');
Then my response from the server looks like this:
{"content":"new content"}
And the content-type is automatically set to text/html. When dataType in the jQuery ajax options is unset, it uses a default of 'intelligent guessing'. I'm strongly assuming that jQuery recognizes the response-data as json because updatePage is parsed an object. updatePage uses the JSON js library(json2.js), and does this:
function updatePage(data) {
$dataObj = JSON.parse(data);
}
When the function is called upon ajax succes, everything works fine. No errors. Here's the strange thing, if I set my header to application/json as above, JSON.parse suddenly reports an error. The exact same error happens if i set my dataType to 'json' in the jQuery ajax request. The response I get from the PHP script when changing these things looks exactly like the one above. The error looks like this in Firebug:
JSON.parse
$dataObj = JSON.parse(data);
Kind of a long one, sorry, but If anyone knows what is wrong their help is greatly appreciated. Thanks for your time.
It's because you end up trying to double-parse the return value.
Both the explicit json
data type and usage of the application/json
MIME type cause jQuery to parse the returned string into a JavaScript object for you.
So, your usage of JSON.parse()
, in these cases, is superfluous.
精彩评论