2012-04-03 77 views
1

如果我有這樣的JSON響應驗證使用JSON - 阿賈克斯

{"error":"repeated"} 

爲什麼警報沒有顯示?它需要放在某個地方dataType: "json"

$(function() { 
     $("#box a").click(function() { 
      var selectedId = $(this).attr("class"); 

      $.post("new_list.php", { 
       id_user: <?php echo $id;?>, 
       id_list: selectedId 
      }, function (data) { 
        if(data.error == 'repeated') { 
         alert("error"); 
        } 
      }); 
     }); 
    }); 

感謝

回答

2

它不會,除非你告訴它自動解析它作爲JSON。

$(function() { 
    $("#box a").click(function() { 
     var selectedId = $(this).attr("class"); 

     $.post("new_list.php", { 
      id_user: <?php echo $id;?>, 
      id_list: selectedId 
     }, function (data) { 
       if(data.error == 'repeated') { 
        alert("error"); 
       } 
     }, 
     "json"); //Here, add this as last parameter 
    }); 
}); 
1

這將是響應字符串轉換成Javascript對象的問題:

function (data) { 
    // Parse the JSON 
    data = JSON.parse(data); 

    if(data.error == 'repeated') { 
     alert("error"); 
    } 
} 

雖然你可以只使用jQuery.getJSON函數來代替,節省自己的一些麻煩

0

檢查您的回覆是一個字符串而不是一個對象。然後,你必須調用

var obj = jQuery.parseJSON(data); 

並使用obj.error檢查它是否是「重複」

0
$(function() { 
     $("#box a").click(function() { 
      var selectedId = $(this).attr("class"); 

      $.post("new_list.php", { 
       id_user: <?php echo $id;?>, 
       id_list: selectedId 
      }, function (data) { 
        if(data.error == 'repeated') { 
         alert("error"); 
        } 
      },dataType: "json"); 
     }); 
    }); 

下面的代碼片斷將讓jQuery的知道你期待JSON。