访问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-Object看起来很糟糕:
[{"messageId":43,"text":"ghstgh"}]
当我现在想要访问文本时:
alert(data[1].text);
我得到了不明确的….
我究竟做错了什么?
最诚挚的问候,Bodo
将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
JavaScript数组从0开始,而不是1。
您的数组只有一个元素,因此您希望使用0
作为索引:
alert(data[0].text);