jQuery AJAX GET/POST 请求在错误处理程序中返回 404,但从服务器发送有效响应

标签 jquery ajax json google-app-engine http-status-code-404

问题:我使用 jQuery.ajax 发送 GET 或 POST 请求,并得到一个用 404 触发的错误处理程序。问题是,我使用嗅探器检查来自服务器的答案,它是一个有效的 200 响应,具有正确的JSON(由 Python json.dumps 返回)。 还有一些奇怪的事情:在这个调用以 404 结束后,浏览器重新加载页面。

一切都在同一个域(和子域)。

jQuery 调用:

$.ajax({type: "POST", url: "/m/auth/login", data: {x: "y"},
success: function(result) {}, error: function(xhr) {}, dataType: "json"});

嗅探器看到的响应,有效负载已解压:

HTTP/1.1 200 OK\r\n
Content-Type: text/html; charset=utf-8\r\n
Cache-Control: no-cache, must-revalidate\r\n
Content-Encoding: gzip\r\n
X-AppEngine-Estimated-CPM-US-Dollars: $0.000018\r\n
X-AppEngine-Resource-Usage: ms=71 cpu_ms=0\r\n
Vary: Accept-Encoding\r\n
Date: Tue, 24 Dec 2013 21:04:36 GMT\r\n
Pragma: no-cache\r\n
Expires: Fri, 01 Jan 1990 00:00:00 GMT\r\n
Server: Google Frontend\r\n
Content-Length: 80\r\n
Alternate-Protocol: 80:quic,80:quic\r\n
\r\n
{"reason": {"password": "missing", "email": "missing"}, "error": "argument"}

最佳答案

服务器响应的内容类型为:text\html 并且您的 ajax 调用需要 json。您需要将响应的 header 设置为 Content-type: application/json。您也可以尝试设置 ajax 调用的 header 以接受 gzip 编码数据。

在 php 中你可以这样做

header('Content-type: application/json');

在回显 json 之前。或者您可以将 ajax 调用的类型设置为文本、html。

还建议像这样使用 jquery 链接回调函数

$.ajax({
    url: '/m/auth/login',
    headers: { "Accept-Encoding" : "gzip" },
    type: 'POST',
    dataType: 'json',//be sure you are receiving a valid json response or you'll get an error
    data: {x: 'y'},
})
.done(function(response) {
    console.log("success");
    console.log(response);
})
.fail(function() {
    console.log("error");
})
.always(function() {
    console.log("complete");
});

关于jQuery AJAX GET/POST 请求在错误处理程序中返回 404,但从服务器发送有效响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20766803/

相关文章:

javascript - JQuery 点击 3 次隐藏按钮

jquery - 动态创建的div定位问题

jquery - +/- icon jQuery 子 Accordion (父元素和子元素)

javascript - 在 IE8 中显示内联 SVG

java - 当我使用 json.encode 时,使用 Vert.x 的 JSON 库时出现问题

javascript - 单击更改 Bootstrap Popover 触发器

java - java Controller 中无法正确识别特殊/重音字符?

javascript - 在客户端过滤嵌套对象

javascript - 使用 JSON 对象填充 DataTable

java - Spring 持久失败,带有 FK 的 JSON,FK null