尝试将标头与您的 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.