The following function causes the response variable to be null in Chrome and Safari, but not in Firefox.
function updatePage(response){ // This argument differs by browser response = jQuery.parseJSON(response); for(var i=0; i<response.length; i++){ // conduct magic }; };
Mistake:
Uncaught TypeError: Cannot read property 'length' of null
This is because loading jQuery.parseJSON () is nothing but a JSON string , returns null. Chrome and Safari seem to automatically parse JSON without an explicit request. If I test the answer argument before trying to parse it using jQuery, it is already a JSON object in both Chrome and Safari. However, in Firefox this is still a line.
The only solution I came across to deal with this in all browsers is to determine if the "answer" 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 at the moment? It seems that jQuery.parseJSON will detect the user agent and simply return the argument as it is with Chrome / Safari.
Relevant Information
- This is jQuery 1.6.1
- Content-Type response from server is application / json
- The response argument comes 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); } });
json jquery
Chris cummings
source share