$.ajax函数的成功处理程序如何处理非标准HTTP状态码?

9
我们编写了一个RESTful服务器API。由于某种原因,我们决定对于DELETE请求,返回状态码204(无内容),并提供空响应。我正在尝试从jQuery中调用它,传递一个成功处理程序并将动词设置为DELETE:
jQuery.ajax({
    type:'DELETE',
    url: url,
    success: callback,
});

服务器返回了204,但成功处理程序从未被调用。有没有办法配置jQuery使204触发成功处理程序?

5个回答

11

204应该被视为成功。您使用的 jQuery 版本是什么?我进行了一些测试,所有 200 范围状态码都会进入成功处理程序。jQuery 1.4.2 的源代码证实了这一点

// 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;
},

好的,现在我有点困惑了。不过我再试了一次,看起来似乎可以运行了。看来之前我可能把其他事情做错了。谢谢! - Bennidhamma

9

我曾经遇到了类似的问题,因为我的脚本也将"Content-Type"标头发送为"application/json"。虽然请求成功了,但它无法解析一个空字符串。


3
jQuery.ajax({
    ...
    error: function(xhr, errorText) {
        if(xhr.status==204) successCallback(null, errorText, xhr);
        ...
    },
    ...
});

丑陋...但可能有帮助


谢谢sje397,那很有道理。你觉得这是唯一的方法吗? - Bennidhamma

3

这实际上是您服务器上的问题
就像Paul所说的那样,带有JSON服务器内容类型的空204响应被jQuery视为错误。

您可以通过手动覆盖dataType为'text'来解决jQuery中的此问题。

$.ajax({
    url: url,
    dataType:'text',
    success:(data){
       //I will now fire on 204 status with empty content
       //I have beaten the machine.
    }
});

2

这是一种在成功回调时的替代方法...我认为这对你有用。

$.ajax({
    url: url,
    dataType:'text',
    statusCode: {
                204: function (data) {
                   logic here
                }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接