This is how jQuery works.
JQuery will assume the response is JSON if either:
- You specify
dataType: 'json'
in the ajax call, or
- You do not include the
dataType
setting but jQuery detects the response is JSON because of a response header.
And when jQuery assumes the response is JSON, it automatically tries to parse the response into objects before it calls the success handler. If the parse fails, the error handler is called instead.
From the jQuery documentation:
As of jQuery 1.9, an empty response is also rejected; the server
should return a response of null
or {}
instead.
I don't know why jQuery couldn't make an exception for an empty response and treat it the same as null
, or even as undefined
, but if you cannot (or won't) change the response, a work-around would be to specify dataType: 'text'
and then parse the response yourself.
$.ajax(url, {
type: 'post',
dataType: 'text',
data: params,
success: function(text) {
if (text) {
var data = jQuery.parseJSON(text);
// ...
}
}
});