0

好的,所以我尝试使用 .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 文档状态。

你有什么建议?

4

2 回答 2

0

检查 Chrome 开发人员工具、Firebug 或开发代理中的标头将显示此处发生的情况:通过 PHP 发送“Location:”标头设置的 302 Found 标头会覆盖原本会发送的 404 错误。结果,没有客户端(包括搜索引擎和本例中的 jQuery 的 AJAX 请求处理程序)知道发生了错误。就他们而言,请求成功并获取了预期的内容(在一次重定向之后)。

发送没有重定向的更简单的 404 将导致更可预测的行为。

于 2011-05-29T23:29:52.820 回答
0

尝试将标头与您的 AJAX 请求一起传递:

$.ajax({url: url, type: "GET", cache: false, headers: {'X-My-AJAX-Header': 'yes'}, error: function(){
 alert("Looking rather erroneous, are we?");
}, success: function(html){
 // ...
}

...然后您可以在error.php, 中检测到以不同方式处理来自 AJAX 请求的错误:

<?php
if (isset($_SERVER['HTTP_X_MY_AJAX_HEADER'])) {
    header('Status: 404');
} else {
    header("Location: /#error");
}
?>

您可能必须尝试使用​​该$_SERVER密钥。另请参阅apache_request_headers您是否使用 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 the Location: 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.

于 2011-05-30T02:58:22.310 回答