2013-06-01 142 views
0

我在JavaScript,JQuery和Ajax編碼的新手。 我正在使用JQuery $ .ajax方法來調用異步REST調用。 不知何故,我無法接收HTTP響應JSON數據。

我可以看到下面的警報結果。 alert(data)方法結果爲[Object Object] alert(data.toSource())方法結果爲({「key1」,「value1」}) alert($。parseJSON(data))方法結果爲空

我已經在firefox和chrome瀏覽器中測試了下面的代碼。

<html> 
<head> 
<title></title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"</script> 
</head> 
<body> 
    <form id="foo"> 
     <label for="bar">A bar</label> 
     <input id="bar" name="bar" type="text" value="" /> 
     <input type="submit" value="Send" /> 
    </form> 
    <!-- the result of the search will be rendered inside this div --> 
    <div id="result"></div> 
    <script> 
     $("#foo").submit(function(event) { 
      event.preventDefault(); 
      $("#result").html(''); 
      var values = $(this).serialize(); 
      $.ajax({ 
       url: "resources/helloWorld", 
       type: "GET", 
       dataType: 'json', 
       success: function(data){ 
        alert(data); 
        alert(data.toSource()); 
        var r = $.parseJSON(data); 
        alert(r); 
        $("#result").html(data); 
       }, 
       error:function(){ 
        $("#result").html('there is error while submit'); 
       } 
      }); 
     }); 
    </script> 
</body> 

+1

要退有效的JSON? – ajtrichards

+0

我的json響應是{「key1」:「value1」} –

+0

你可以發佈甚至是json文件。這將很容易分析。 – iraycd

回答

2

從您的帖子:

alert(data) -> [Object Object] 

右鍵,alert()使用參數的描述,同時data是一個對象。

alert(data.toSource()) -> ({"key1","value1"}) 

右鍵,toSource()是壁虎的方法,它作爲JSON.stringify

alert($.parseJSON(data)) method result is nothing 

對,你正試圖解析一個對象。


你想要做的是一樣的東西也許是:

success: function(data){ 
    $("#result").html(data.key1); 
} 
+0

感謝您的幫助。是的,它適用於我。我想接收整個JSON響應並解析這個JSON。因爲我的JSON非常複雜。我不能使用$ .parseJSON方法來解析我的HTTP響應嗎? –

+0

@RaviHingarajiya你的json已經被解析了。在'success'函數內運行'console.log(data)'來檢查它。 – moonwave99