在 .htaccess 中设置 ErrorDocument 404 会导致 jQuery 的 AJAX 调用永远不会出错
好吧,所以我尝试使用 .htaccess 为各种错误代码设置 ErrorDocuments。它工作得很好,只是现在,以下 jQuery AJAX 代码将永远不会运行 error() 函数:
$.ajax({url: url, type: "GET", cache: false, error: function(){
alert("Looking rather erroneous, are we?");
}, success: function(html){
// ...
}
有什么建议吗?我想我知道原因: .htaccess 指向所有错误,如下所示:
ErrorDocument 404 /error.php
并且 /error.php 有以下内容:
<?php header("Location: /#error"); ?>
因此,当它传输到 index.php 时,它可能会丢失 404 文档状态。
你有什么建议?
Alright, so I tried to use .htaccess to set up ErrorDocuments for various error codes. It works great, except that now, the following jQuery AJAX code will never run the error() function:
$.ajax({url: url, type: "GET", cache: false, error: function(){
alert("Looking rather erroneous, are we?");
}, success: function(html){
// ...
}
Any proposals? I think I know the reason why: .htaccess points all errors like so:
ErrorDocument 404 /error.php
And /error.php has the following:
<?php header("Location: /#error"); ?>
So when it transfers to index.php, it probably loses the 404 document status.
What would you suggest?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查 Chrome 开发者工具、Firebug 或开发代理中的标头将显示此处发生的情况:通过 PHP 发送“Location:”标头设置的 302 Found 标头会覆盖原本会发送的 404 错误。因此,没有客户端(包括搜索引擎以及本例中的 jQuery 的 AJAX 请求处理程序)知道发生了错误。就他们而言,请求成功并获取了预期内容(一次重定向后)。
发送更简单的 404 而不重定向将导致更可预测的行为。
Checking the headers in Chrome Developer Tools, Firebug, or a development proxy will show what's happening here: The 302 Found header set by sending a "Location:" header by PHP overrides the 404 error that would otherwise be sent. As a result, no client (including search engines and also jQuery's AJAX request handler in this case), knows that an error occurred. As far as they're concerned the request was successful and picked up the intended content (after one redirect).
Sending a simpler 404 without redirect will result in more predictable behavior.
尝试将标头与您的 AJAX 请求一起传递:
...然后您可以在
error.php
中检测到该标头,以不同方式处理来自 AJAX 请求的错误:您可能必须尝试该
$ _SERVER
键。如果您使用的是 Apache/mod_php,另请参阅apache_request_headers
。编辑:
您需要执行此操作的原因是,如下所述,
header("Location: /#error");
发送一个 302(重定向)标头,该标头覆盖 404(未找到)。您无法使用Location:
标头在 404 上重定向(它仅适用于 3xx),并且只能发送一种状态。 JQuery 将(正确地)仅在错误状态下触发错误回调;这些都是4xx。维基百科对此的解释非常好。
Try passing a header along with your AJAX request:
...which you can then detect in your
error.php
, to treat errors from AJAX requests differently:You may have to experiment with that
$_SERVER
key. See alsoapache_request_headers
if you're using Apache/mod_php.EDIT:
The reason you need to do this is, as stated below, the
header("Location: /#error");
sends a 302 (redirect) header, which overrides the 404 (not found). You can't use theLocation:
header to redirect on a 404 (it only works on 3xx) and you can only send one status. JQuery will (correctly) only trigger the error callback on an error status; these are all 4xx.Wikipedia's explanation of this is very good.