We've written a RESTful server API. For whatever reason, we made the decision that for DELETEs, we would like to return a 204 (No Content) status code, with an empty response. I'm trying to call this from jQuery, passing in a success handler and setting the verb to DELETE:
jQuery.ajax({
type:'DELETE',
url: url,
success: callback,
});
The server returns a 204, but the success handler is never called. Is there 开发者_StackOverflowa way I can configure jQuery to allow 204s to fire the success handler?
204
should be treated as success. What version of jQuery are you using? I did a couple of tests and all 200 range status codes went to the success handler. The source for jQuery 1.4.2 confirms this:
// Determines if an XMLHttpRequest was successful or not
httpSuccess: function( xhr ) {
try {
// IE error sometimes returns 1223 when
// it should be 204 so treat it as success, see #1450
return !xhr.status && location.protocol === "file:" ||
// Opera returns 0 when status is 304
( xhr.status >= 200 && xhr.status < 300 ) ||
xhr.status === 304 || xhr.status === 1223 || xhr.status === 0;
} catch(e) {}
return false;
},
I had a simliar issue because my script was also sending the "Content-Type" header as "application/json". While the request succeeded, it couldn't JSON.parse an empty string.
jQuery.ajax({
...
error: function(xhr, errorText) {
if(xhr.status==204) successCallback(null, errorText, xhr);
...
},
...
});
ugly...but might help
It's technically a problem on your server
Like Paul said, an an empty 204 response with a server content-type of json is treated by jQuery as an error.
You can get around it in jQuery by manually overriding dataType to 'text'.
$.ajax({
url: url,
dataType:'text',
success:(data){
//I will now fire on 204 status with empty content
//I have beaten the machine.
}
});
This is alternative way to callback on success... I think that will work for you.
$.ajax({
url: url,
dataType:'text',
statusCode: {
204: function (data) {
logic here
}
});
精彩评论