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 エラー ハンドラでこれら 2 つのデータを取得できます。

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 に答える