在 jQuery 的 $.ajax 方法中,error 回调函数的触发有多种原因,对于服务器而言,就是 4XX 或 5XX 系列的状态码响应即可。
// 构建&输出 Response Header 头信息$code = 500;
$errormessage = 'Internal Server Error';
$status_header = 'HTTP/1.1 ' . $code . ' ' . $errormessage;
header($status_header);
// 输出Response body
$data = array('msg' => 'this is error message');
echo json_encode($data);exit;<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery test</title>
</head>
<body>
<button id="click">Click Me</button>
<script src="jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$('#click').click(function () {
$.ajax({
url: 'http://localhost/demo.php',
error: function (XMLHttpRequest, textStatus, errorThrown) {
var errorMsg = jQuery.parseJSON(XMLHttpRequest.responseText);
console.log(textStatus);
console.log(errorThrown);
console.log(errorMsg);
}
});
});
</script>
</body>
</html>
如果只是要进入 error 回调函数,状态码是 4xx, 5xx 都可以
<?php
$code = 400;
$errormessage = 'Bad Request';
$status_header = 'HTTP/1.1 ' . $code . ' ' . $errormessage;
header($status_header);
$data = array('msg'=>'自定义错误信息或数据');
exit(json_encode($data));