【发布时间】:2014-07-25 07:57:06
【问题描述】:
我正在尝试使用 Ajax 向 Url 发出 POST 请求。我的 JS/JQuery 代码如下所示
var params = {
'username' : 'eddard.stark@got.com',
'name' : 'Eddard Stark'
};
$.post("/user/add", params, function(data) {
// no errors
var user = eval('(' + data + ')');
$("#spanId").html("User Id " + user.id);
// Here - http://stackoverflow.com/questions/16472116/ajax-error-cannot-catch-thrown-exception-from-php
// they are saying that it can be handled here. But How?
}).fail(function(err, status) {
// error 4xx : client side errors (e.g. controller/action does not exist)
// error 5xx : server side errors (like db failure)
$("#spanId").html("Error " + err);
}).always(function() {
$(elm).hide();
$('#spanId').show();
});
/user/add 动作的 PHP 代码是
function add()
{
$username = null;
$name = null;
if (!empty($_POST)) {
if (isset($_POST['username']) { $username = $_POST['username']; }
if (isset($_POST['name']) { $name = $_POST['name']; }
}
if (is_null($username) || is_null($name)) {
throw new Exception('Invalid request');
}
$user = $this->User->search($username);
if (isset($user)) {
thorw new Exception('User not available');
}
// ... more code ...
}
如何在 Ajax 中打印这些异常?
编辑:
还有另一种处理方法。在抛出异常之前设置下面的标题
header("HTTP/1.1 400 User not available");
// throw exception
然后我的 Ajax 代码中的 fail 处理程序可以像这样打印它
$("#spanId").html("Error : " + err.statusText)
但我不想这样做。我想在 success 处理程序本身中打印它。
【问题讨论】:
-
创建一个变量$exception。在您的异常 ifs 中,根据需要更改 $exception 的值。然后将您的 $exception 与其他已经存在的变量一起发送到 ajax。然后检查ajax中$exception的值,必要时处理
-
查看这里:: stackoverflow.com/questions/2809963/… 以获得答案
-
为什么异常不被认为是错误?是否有其他处理程序?