In my $.ajaxSucess() function I need to find out if the response is json. Currently I am doing this:
$('body').ajaxSuccess(function(evt, xhr, settings) {
var contType = xhr.getAllResponseHeaders().match(/Content-Type: *([^)]+);/);
if(contType && contType.length == 2 && contType[1].toLowerCase() == 'application/json'){
...
Is there a better way?
getJSON( url, [data], [callback] ) method loads JSON data from the server using a GET HTTP request. The method returns XMLHttpRequest object.
Response is the object passed as the first argument of all Ajax requests callbacks. This is a wrapper around the native xmlHttpRequest object.
Assuming that you are expecting json, I'd simply try and parse it like json and catch any errors. Also see jQuery.parseJSON.
try {
jQuery.parseJSON(response);
} catch(error) {
// its not json
}
If you are expecting one of a number of different response types (i.e. it might be json or it might just be text, etc) then you might need to get more complicated. I'd use xhr.getResponseHeader("content-type"). See this blog post for some great detail on handling content types.
$.ajax({
type: "POST",
url: "/widgets",
data: widgetForm.serialize(),
success: function(response, status, xhr){
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf(‘html’) > -1) {
widgetForm.replaceWith(response);
}
if (ct.indexOf(‘json’) > -1) {
// handle json here
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With