【问题标题】:jQuery AJAX GET/POST request returns 404 in error handler, but valid response is sent from serverjQuery AJAX GET/POST 请求在错误处理程序中返回 404,但从服务器发送了有效响应
【发布时间】:2014-01-13 01:05:03
【问题描述】:

问题:我使用 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"}

【问题讨论】:

  • 我不确定我是否了解客户在这里遇到的一系列事件。客户端从 App Engine Python 应用程序加载页面。该页面使用jQuery.ajax 向应用程序发出异步HTTP 请求。该应用程序为 200 提供正确的 JSON 正文。 jQuery 将响应误解为 404 并重新加载页面?以上是正确的吗?您是否使用Chrome Developer Tools 来验证请求/响应?什么告诉你它正在接收 404?

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


【解决方案1】:

内容类型的服务器响应:text\html 并且您的 ajax 调用需要 json。您需要将响应的标头设置为 Content-type: application/json。您也可以尝试设置 ajax 调用的标头以接受 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");
});

【讨论】:

  • 我之前试过设置content-type为application/json,没关系,还是404。毕竟设置dataType:"json"时,jQuery会忽略content-type。
  • 尝试将标头设置为接受 gzip 编码的响应。更新了我的答案。
  • 好吧,我在嗅探器中看到 jQuery 发送的请求正在接受 gzip 编码的响应,因为它必须是别的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-09
  • 2016-03-06
相关资源
最近更新 更多