Set the request statuscode in the php response to 4XX or 5XX. That will make you end up in the error
/fail
callback.
I dones't necessarily have to be a value in the list. For example, you can create your own:
StatusCode: 550
StatusText: "My Custom Error"
Which, if I recall correctly, would look like this in PHP:
header('HTTP/1.0 550 My Custom Error');
Finally, send the error details to the client to notify them of what went wrong. You can either place the info in the header, or serialize the exception using json_encode()
<?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(),
),
));
}
?>
Client side:
$.ajax({
url: 'page.php',
data: { 'some_bad_condition': true }
}).done(function(data){
console.log('success!', data);
}).fail(function(jqXhr){
var errorObject = $.parseJSON(jqXhr.responseText);
console.log('something went wrong:', errorObject);
//jqXhr.status === 550
//jqXhr.statusText === 'My Custom Error'
});
Don't forget to specify the correct mimetype in your PHP file. That way jQuery will know that it's a JSON response without you specifying it explicitly.
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…