从PHP抛出的Ajax中打印异常

时间:2014-07-25 07:57:06

标签: php jquery ajax

我正在尝试使用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处理程序本身打印它。

1 个答案:

答案 0 :(得分:0)

这里有一点我的评论。

你的ajax中的

.done(function (response) { 


                if( (response.exception) === "noExp" )
                {
                        alert("success!!!");
                        //no exception
                }
                else
                {
                        //handle it
                }
}

在php中

function add() 
{
    $username = null;
    $name = null;
    $exception = "noExp";
    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');
        $exception = "invalid request";
    }
    $user = $this->User->search($username);
    if (isset($user)) {
        //thorw new Exception('User not available');
        $exception = "User not available";
    }
    // ... more code ...
    $result = array(
        "exception" => $exception,
         //other returns
    )
    echo json_encode($result);

}