我正在使用 JQuery 调用 PHP 函数,该函数在成功时返回 JSON 字符串或引发一些异常。目前我正在打电话jQuery.parseJSON()
在响应上,如果失败,我假设响应包含异常字符串。
$.ajax({
type: "POST",
url: "something.php",
success: function(response){
try {
var json = jQuery.parseJSON(response);
}
catch (e) {
alert(response);
return -1;
}
// ... do stuff with json
}
谁能建议一种更优雅的方式来捕获异常?
非常感谢,
伊塔马尔
捕获 PHP 脚本中的异常 - 使用try .... catch
块 - 当发生异常时,让脚本输出带有错误消息的 JSON 对象:
try
{
// do what you have to do
}
catch (Exception $e)
{
echo json_encode("error" => "Exception occurred: ".$e->getMessage());
}
然后,您将在 jQuery 脚本中查找错误消息,并可能将其输出。
另一种选择是发送500 internal server error
PHP 遇到异常时的标头:
try
{
// do what you have to do
}
catch (Exception $e)
{
header("HTTP/1.1 500 Internal Server Error");
echo "Exception occurred: ".$e->getMessage(); // the response body
// to parse in Ajax
die();
}
然后,您的 Ajax 对象将调用错误回调函数,您将在其中进行错误处理。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)