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

Art*_*xes 5 ajax jquery google-app-engine json 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"});
Run Code Online (Sandbox Code Playgroud)

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

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"}
Run Code Online (Sandbox Code Playgroud)

kas*_*ans 2

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

在 php 中你可以这样做

header('内容类型:application/json');

在回显 json 之前。或者您可以将 ajax 调用的类型设置为 text、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");
});
Run Code Online (Sandbox Code Playgroud)