问题
I've got some jQuery (1.6.2, latest stable) code which is working in Chrome, Firefox, Safari, IE7 and IE8... but IE9 is failing to parse my json ajax response. The json is valid and I've run it through http://jsonlint.com/
$.ajax({
url: lookupURL,
dataType: "json",
cache: false, // don't cache the result
contentType: "application/json", //tell the server we're looking for json
success: function(data) {
// do stuff with result
},
error: function(xhr, errorString, exception) {
alert("xhr.status="+xhr.status+" error="+errorString+" exception=|"+exception+"|");
}
});
The error handler is the one jQuery calls (IE9 only). The xhr.status=200, the errorString=parseerror and the exception=SyntaxError JSON.parse
My json IS valid and I've even checked with using an ultimately simple json string:
{"foo":"bar"}
I have verified using xhr.responseText that there are no leading or trailing spaces on the json.
Why is this failing in IE9?
回答1:
Found the problem. The system I'm working with is a fairly large CMS and E-Commerce framework, so they have a LOT of javascript in their own libraries. Deep inside one of their js libraries they were replacing the global JSON object and providing their own implementation of JSON.parse. It looks like it was an older and/or hacked version of json2 from json.org. When trying to solve the problem earlier, I had tried installing json2 as the JSON object to no avail... but it turned out they were then clobbering my json2 with theirs. I moved my installation of json2 to be the last javascript loaded and now it is working. I don't know what IE9 was the only one affected... but there you go.
回答2:
A couple of things for you to try, but first remove the contentType for now as I don't think you need it to work out your bug.
1) From here: http://api.jquery.com/jQuery.ajax/ dataType "As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require." So you could try your dataType as 'text json'
2) Is your json trimmed (no whitespace around it) ?
3) Have you tried it (at least as a test) using getJSON() ?
来源:https://stackoverflow.com/questions/7182732/jquery-ie9-json-syntaxerror-parseerror-but-json-is-valid