【问题标题】:jQuery .ajax: How to handle Custom Validation Error Message, REST API, 400 status code?jQuery .ajax:如何处理自定义验证错误消息、REST API、400 状态码?
【发布时间】:2013-06-11 03:24:15
【问题描述】:

从 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。

【问题讨论】:

  • 400 是“错误请求”错误代码。

标签: php jquery rest


【解决方案1】:

在 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 编码的数据),具体取决于服务器端发生的情况。

【讨论】:

  • 是的,后来我发现我需要的数据在 jqXHR.responseText 中,当应用 parseJSON() 时,它给了我我的数据对象。然后我可以使用自定义验证消息 -> response.message。
【解决方案2】:

当这种情况发生时,我讨厌它。 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>');
}   

【讨论】:

    猜你喜欢
    • 2010-09-27
    • 2011-10-22
    • 2012-09-25
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 2018-02-08
    相关资源
    最近更新 更多