javascript - 将自定义错误代码传递给ajax错误函数

标签 javascript php jquery ajax

我正在尝试将自定义错误代码传递到客户端的 ajax 错误函数。 在服务器端:

$response = array();

if ( empty($post['parent_id']) ) {
    $response = array('error' => true, 'status_code' => -2);
    exit();
}

$is_valid_id = RC()->is_valid_id($post['parent_id']);
$row = RC()->get_row_data($post['parent_id']);
if ( ! $is_valid_id ) {
    $response = array('error' => true, 'status_code' => -1);
} else if ( ! $row ) {
    $response = array('error' => true, 'status_code' => 0);
} else {
    $response = json_encode($row);
}

echo $response;

然后我想在我的js脚本中检查此状态代码,但找不到方法来执行此操作(找到的方法仅不触发错误事件)。

$.ajax({
    url: ajax_url,
    data: {
        'action': 'rc_parent_sign_in',
        'form_data': $('#parent-sign-in-form').serialize(),
        'security': security_nonce
    },
    type: "post",
    dataType: "json",
    cache: false,
    success: function (response) {
        var query_vars = $.param(response);
        window.location.replace('http://localhost/renecassin/user-registration/?' + query_vars);
    },
    error: function (response) {
        $('.form-control-feedback').addClass('hide');

        /* Looking for something like this */
        switch ( response.status_code) {
            case -2 :
                parent_id_form_group.addClass('has-danger').children('#empty-field').
                removeClass('hide');
                prent_id_input.addClass('form-control-danger');
                break;
            case -1 :
                parent_id_form_group.addClass('has-danger').children('#not-valid-id-feedback').
                removeClass('hide');
                prent_id_input.addClass('form-control-danger');
                break;
            default :
                parent_id_form_group.addClass('has-danger').children('#id-not-exists-feedback').
                removeClass('hide');
                prent_id_input.addClass('form-control-danger');
        }
    }
});

任何帮助将不胜感激。

最佳答案

这是因为响应将转到您的响应回调,您成功返回了一个对象。

仅当请求本身失败(超时、404 等)时才会调用错误回调

您需要在成功回调中处理内部错误代码

关于javascript - 将自定义错误代码传递给ajax错误函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43704334/

相关文章:

php - 模式匹配,不以零开头

javascript - 如何在 D3 中添加(自定义)千位分隔符?

javascript - PHP preg_match 从 javascript 获取值

javascript - 表中的 ng-repeat datepickers 提示 'missing instance data' 错误

javascript - jQuery EasyUI : confirmation on close window

javascript - jquery将来自url的json对象存储在javascript变量中

javascript - 动画随机平铺背景

javascript - Material UI 如何设置网格元素垂直跨3行?

php - 使用 PHP Reflection 获取非静态的公共(public)属性

php - fatal error : Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error' in