Reputation: 5721
I'm not a front-end developer, and I'm working on a casual project, which requires AJAX getting a piece of JSON.
$('#btn1').click(function() {
$.ajax({
url: 'http://mywebsite.com/persons/mike',
type: "get",
success: function(response, textStatus, jqXHR){
var age1 = JSON.parse(response).data.age; // works for Firefox
var age2 = response.data.age; // works for Chrome
},
error: function(jqXHR, textStatus, errorThrown){
console.log('Error')
},
complete: function(){
console.log('Complete')
}
});
});
I use Firebug in Firefox and Developer Tools in Chrome. The response
is of type Object
in Chrome, and is a String
in Firefox.
Is there a generic way to do AJAX in jQuery and successfully parse the response?
Upvotes: 2
Views: 3417
Reputation: 70159
Set dataType: 'json'
in your $.ajax
.
This will force the response inside the success
/done
handler to be an already parsed object, else, in case the response is not valid JSON, the error
/fail
handler will be called.
Note: Using dataType
will force the response to be parsed as JSON even if you don't specify a Content-Type: application/json
header in the response.
If you specify the header though, jQuery.ajax
's Intelligent Guess would parse the response as an object even if you don't specify the dataType
.
So, you can either use the dataType: 'json'
in $.ajax
or output the header Content-Type: application/json
from the back-end and it will work fine. Or both if you want to be throughout. =]
Upvotes: 7