I have a really simple chat application on a site which works pretty good.
It requests by ajax like this:
$.ajax({
url: "fetch/"+CHAT_SESSION_ID+"/"+LAST_MESSAGE_ID,
dataType: "json",
cache: false,
success: function(data) {
if (data.session_active == 0) { //If other chatter ended session
alert("Session Ended");
}
else
{
$.each(data.messages, function(i,msg){
alert(msg.message.Body);
)};
}
}
});
and gets a json response that lookes like this:
{ "session_active": "1", "messages": [ {"message": {"MsgID": "100", "UserID": "1", "Body": "heyy"}}, ]}
It开发者_运维百科 works really well in at least FF and Saf but in Chrome it never gets past the .each!
This is driving me nuts, have tried everything I've come across online for days but I can't seem to get it right.
Please someone help! I can provide testserver if someone wants to firebug it themselves ;)
Perhaps the trailing comma in your messages array is causing an issue. See the responses to the following question:
Can you use a trailing comma in a JSON object?
Possible incorrect mimetype: If you look at jQuery's parsing code, it seems that if the JSON data isn't a string passed to $.parseJSON(data)
then it returns null
. This might be a problem as if the AJAX response's mimetype is incorrectly identified by Chrome and it doesn't interpret the AJAX response as text, it'll return null
and therefore pass null
to the AJAX function. The mimetype served with the AJAX response (or possibly lack of one) may therefore also be the problem:
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
.replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {
// Try to use the native JSON parser first
return window.JSON && window.JSON.parse ?
window.JSON.parse( data ) :
(new Function("return " + data))();
} else {
jQuery.error( "Invalid JSON: " + data );
}
},
Malformed JSON: The other reason why this might work in Firefox and other browsers but not Google Chrome is the jQuery parse function tries to use the native window.JSON.parse(data)
function over new Function("return " + data)
if native JSON parsing is available in that browser.
Google Chrome's parsing may be more strict than Firefox is at having things like trailing commas as specified by the standard at http://www.json.org/ as stated in Danilo Celic's answer.
精彩评论