簡體   English   中英

使用jQuery檢查來自AJAX響應的JSON字符串

[英]Check JSON string from AJAX response with jQuery

我在我的聯系表單上使用jQuery來構建我們正在構建的Web應用程序,我從服務器獲得JSON響應:

{"success": true}

到目前為止,這是我的jQuery:

$('.contact-form').on('submit', function(e) {

            // Prevent submitting
            e.preventDefault();

            // Loading from data-* attr
            var $submit = $('#contact-submit');
            $submit.html($submit.data('text'));

            // Form data
            var form      = $(this);
            var post_url  = form.attr('action');
            var post_data = form.serialize();

            // Ajax call
            $.ajax({
                type    : 'POST',
                url     : post_url,
                data    : post_data,
                dataType: 'json',
                success: function(){

                },
                error: function(){

                }
            });

        });

在“成功”jQuery方法之前,我從來沒有“檢查過”JSON響應,我可以幫上這個嗎? 我正在尋找一種方法來檢查我得到的響應,如果顯示“是”,我將顯示“已發送成功”消息。

成功回調將獲得json對象作為第一個參數,您可以在回調中使用它,如下所示

$.ajax({
    type : 'POST',
    url : post_url,
    data : post_data,
    dataType : 'json',
    success : function(data) {
        if(data.success){
            //do something if success
        }

    },
    error : function() {

    }
});

為什么不用例如HTTP代碼200(OK)或201(Created)來回復服務器。 然后在jQuery中自動落入成功參數就是一切順利的地方。

當服務器出錯時,使用例如代碼422(Unprocessable Entity),然后jQuery ajax將自動出錯。

如果這是不可能的,只需嘗試使用JSON.parse(數據)解析並沿着樹向下走。 如果解析失敗,json無效。

假設Java后端,您的回復看起來像這里描述的: 如何為Java RESTful Web服務發送HTTP錯誤? ; 這實際上取決於您使用的類/框架。 例如,將HttpReponse狀態設置為422。

你的ajax調用看起來像:

$.ajax({
    type    : 'POST',
    url     : post_url,
    data    : post_data,
    dataType: 'json',
    success: function(){
        // Everything went okay
    },
    statusCode: {
        422: function() {
            // Something went wrong (error in data serverside)
        }
    }
});

以下應該有效:

success: function(result) {
  var thing = $.parseJSON(result.d);
  if (thing.success) {

  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM