jquery - 如何从 jQuery Ajax 获取 304 而不是 200?

标签 jquery

我的服务返回 304,但 jQuery Ajax 似乎将其转换为 200 OK 结果。

这是我的要求:

$.ajax({    
    url: '/api/items',    
    type: 'GET',    
    dataType: 'json',    
    contentType: 'application/json',    
    ifModified:true,    
    cache: false,    
    statusCode: {    
        304: function() {    
            alert("not modified"); // does not fire
        }    
    },    

    complete: function (xhr, status) {    
        console.log(xhr.status); // 200 
        }    
    }    
});

使用 Fiddler,我可以看到该服务正确返回 304

为什么 jQuery 将其转换为 200

最佳答案

如果您想区分它们,请使用 success(data, textStatus, jqXHR) 事件并从 jqXHR.status 读取它

或以其他方式访问jqXHR:

var jqxhr = $.ajax(
    ...     
    statusCode: {    
        200: function() {    
            if(304 == jqxhr.status)
                alert("not modified"); // does not fire
        }    
    },    
)

Proper way to handle 304 not modified in jQuery ajax

编辑

附加ajax()设置:

ifModified:true, // Lets respond `304:notmodified`

但它破坏了数据响应:

http://forum.jquery.com/topic/how-to-fix-browser-cache-and-notmodified-respond-for-json-jquery-ajax-ifmodified-true-break-on-data-respond

但是您已经使用了它,但它的工作方式仍然不同:-/

关于jquery - 如何从 jQuery Ajax 获取 304 而不是 200?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10579510/

相关文章:

jQuery:为什么我的 li 元素上的单击事件不起作用?

javascript - 在 jquery 中启用/禁用文本框

jquery - 如何编写 HTML 结构的 Cheerio 查询?

javascript - 使用箭头键导航输入

javascript - 下面代码中的输出是如何变成1的,谁能解释一下吗?

javascript - 我应该将对象文字存储在 jQuery 命名空间还是全局命名空间中?

jquery - 简单展开/折叠 div > JQuery?

jquery - 在不使用 $.GET 的情况下在 HTML 中内联 SVG

javascript - 如何增加关闭日期取决于选择下拉日期选择器

php - 如何在 Javascript 中使用 PHP