The following function results in the response variable being null in Chrome and Safari but not Firefox.
function updatePage(response){ // This argument differs by browser
response = jQuery.parseJSON(response);
for(var i=0; i<response.length; i++){
// conduct magic
};
};
Error:
Uncaught TypeError: Cannot read property 'length' of null
This is because feeding jQuery.parseJSON() anything but a JSON string returns null. It seems Chrome and Safari automatically parse JSON without explicitly being requested. If I test the “response” argument before trying to parse it with jQuery, it’s already a JSON object in both Chrome and Safari. However, in Firefox it’s still a string.
The only solution I’ve come up with to handle this across browsers is to determine if “response” has already been parsed by checking its constructor:
function updatePage(response){
if(response.constructor === String){
response = jQuery.parseJSON(response);
};
for(var i=0; i<response.length; i++){
// conduct magic
};
};
Am I missing something or is this the only way to handle this currently? Seems like jQuery.parseJSON would detect the user-agent and just return the argument as-is in the case of Chrome/Safari.
Pertinent information
- This is jQuery 1.6.1
- The response Content-Type from the server is application/json
- The response argument is originating from your standard jQuery AJAX call:
$.ajax({
url: API_URL + queryString + '&limit=' + limit,
type: 'GET',
cache: false,
context: document.body,
success: updatePage,
error: function(err){
console.log('ERROR: ' + err);
}
});
It’s not Chrome or Safari, it’s jQuery that does the parsing if it sees the appropriate
Content-Typeon the response. (Update: And theContent-Typeyou’ve added to the question is correct.) I can’t immediately see why it wouldn’t be doing it on Firefox.You can force it to always do the parsing by adding
dataType: 'json'to your call, details in thejQuery.ajaxdocs. Then you wouldn’t callparseJSONat all,responsewould already be the deserialized object.