2

使用从 jQuery .ajax 调用到 REST API 的自定义错误消息(简单文本)处理 400 错误(表单验证错误)的最佳方法是什么。我正在尝试使用响应数据返回验证消息。但是,如果我返回 400 的状态代码,则 .ajax 使用了错误函数。只有成功似乎才能轻松提取“响应”数据,其中包括我的“消息”。

REST API PHP CodeIgniter 的片段:

    $id = $this->contact_model->insert($put);

    if (!empty($id))
    {
        $this->response(array('result' => true, 'id' => $id), 200);
    }
    else
    {
        $this->response(array('result' => false, 
                   'message' => strip_tags(validation_errors())), 400);
    }

jQuery .ajax 代码片段:

$.ajax({
url: '<?php echo site_url('rest_api/contacts')."?format=json"; ?>',
type: "put",
data: $('#subpanel-contacts-add-form').serialize(),
success: function(response) {
    if (response.result == true) {
        // Add Relationship collection_contact_put
        $.ajax({
            url: '<?php echo site_url('rest_api/collections'); ?>/' + collection_id + '/contacts/' + response.id + '?format=json',
            type: "put",
            data: {},
            success: function(relresponse) {
            }
        });
    } else {
        $("#subpanel-contacts-form-result").html('<div class="alert alert-error">Error: The Contact could not be saved! ' + response.message + '</div>');
    }
},
error: function() {
    $("#subpanel-contacts-form-result").html('<div class="alert alert-error">Error: There was an error while submitting!</div>');
}   
});

我正在尝试使用“响应”对象;参数消息和结果。我不确定是否有更好的方法来处理错误代码的响应。我应该使用 .done .always 和/或 .fail。我应该基于返回的状态码吗?

编辑:注意到我混合了 PUT/POST。

4

2 回答 2

3

在 PHP 中,您可以设置自定义状态代码/消息:

header("HTTP/1.1 $statusCode $message");

在哪里

  • $statusCode = 您希望发送的 HTTP 状态代码(自定义错误使用 521-529)
  • $message = 描述错误的文本字符串。

在客户端,您可以在 ajax 错误处理程序中获取这两条数据,如下所示:

error: function(jqXHR, textStatus, errorThrown) {
    var HTTP_status = jqXHR.status;
    var message = errorThrown;
    ...
}

jqXHR.responseText根据服务器端发生的情况,还可能包含有意义的字符串(或 json 编码的数据)。

于 2013-06-10T11:01:16.593 回答
0

当这种情况发生时,我讨厌它。30 分钟后,我想我找到了一种输出失败响应消息的方法。我仍然不确定这是否是最好的方法。我很想听听其他人对这个问题的看法。

error: function (jqXHR, textStatus, errorThrown) {
    response = jQuery.parseJSON(jqXHR.responseText);
    $("#subpanel-contacts-form-result").html('<div class="alert alert-error">Error: There was an error while submitting! ' + response.message + '</div>');
}   
于 2013-06-10T05:35:04.370 回答