2012-03-18 29 views
0

訪問JSON沒有我使用Ajax來獲得一個JSON更新工作

$(document).ready(function(){ 
    $('form').submit(function(event){ 
     event.preventDefault(); 
     var form = JSON.stringify($('form').serializeArray()); 

     $.ajax ({ 
      url: '{{ path('PUSChatBundle_add') }}', 
      type: 'POST', 
      data: form, 
      contentType: 'application/json', 
      success: function(){ 
       $.get('{{ path('PUSChatBundle_refresh') }}', function(data){ 
        alert(data[1].text); 
       }); 
      } 
     }); 
    });   

});  

下面是壞接收JSON-對象看起來是這樣的:

[{"messageId":43,"text":"ghstgh"}] 

,當我現在想與訪問文本:

alert(data[1].text); 

我得到了一個未定義....

我做錯了什麼?

最好的問候, 博多

+0

數組的第一元件具有索引0 - 未1. – powerbuoy 2012-03-18 17:27:03

+0

而不是使用'alert'使用幾乎所有現代瀏覽器都附帶的JavaScript控制檯,並使用'console.log(data);'然後您可以檢查變量並確切看到回調中返回的內容 – JaredMcAteer 2012-03-18 17:49:19

回答

2

dataType設置爲json以便響應被解析

success: function(){ 
       $.get('{{ path('PUSChatBundle_refresh') }}', function(data){ 
        alert(data[0].text); 
       },'json'); //<-- specify the dataType 
      } 

或手動解析JSON

success: function(){ 
       $.get('{{ path('PUSChatBundle_refresh') }}', function(data){ 
        var json = $.parseJSON(data); //<- parse json 
        alert(json[0].text); 
       }); 
      } 

例如:

var j='[{"messageId":43,"text":"ghstgh"}]'; 
var json = $.parseJSON(j); 
console.log(json[0].text); // or alert(json[0].text); 

DEMO

+0

謝謝你這樣做:D – bodokaiser 2012-03-18 17:48:50

+0

很高興幫助... – Rafay 2012-03-18 17:49:36

2

JavaScript數組從0開始,而不是1

2

你的數組只有一個元素,所以你要使用0爲您指數:

alert(data[0].text); 
+0

這也返回給我一個未定義的... – bodokaiser 2012-03-18 17:35:48

+2

@ user1246987你將不得不解析json響應或將'dataType'設置爲'json' – Rafay 2012-03-18 17:45:44