Ja͢*_*͢ck 57
你可以在PHP中做这样的事情(假设这是通过AJAX调用的):
<?php
try {
if (some_bad_condition) {
throw new Exception('Test error', 123);
}
echo json_encode(array(
'result' => 'vanilla!',
));
} catch (Exception $e) {
echo json_encode(array(
'error' => array(
'msg' => $e->getMessage(),
'code' => $e->getCode(),
),
));
}
Run Code Online (Sandbox Code Playgroud)
在JavaScript中:
$.ajax({
// ...
success: function(data) {
if (data.error) {
// handle the error
throw data.error.msg;
}
alert(data.result);
}
});
Run Code Online (Sandbox Code Playgroud)
您还可以error:通过返回400(例如)标头来触发$ .ajax()的处理程序:
header('HTTP/1.0 400 Bad error');
Run Code Online (Sandbox Code Playgroud)
或者Status:如果您使用的是FastCGI,请使用.请注意,error:处理程序不会收到错误详细信息; 要完成你必须覆盖如何$.ajax()工作:)
Facebook在他们的PHP SDK中做了一些事情,如果HTTP请求因任何原因失败,他们会抛出异常.您可以使用此方法,并在抛出异常时返回错误和异常详细信息:
<?php
header('Content-Type: application/json');
try {
// something; result successful
echo json_encode(array(
'results' => $results
));
}
catch (Exception $e) {
echo json_encode(array(
'error' => array(
'code' => $e->getCode(),
'message' => $e->getMessage()
)
));
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以error在JavaScript中监听AJAX调用中的键:
<script>
$.getJSON('http://example.com/some_endpoint.php', function(response) {
if (response.error) {
// an error occurred
}
else {
$.each(response.results, function(i, result) {
// do something with each result
});
}
});
</script>
Run Code Online (Sandbox Code Playgroud)