我正在使用 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);
我变得不确定......
我究竟做错了什么?
此致,
博多
set the dataType
to 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);
});
}
example:
var j='[{"messageId":43,"text":"ghstgh"}]';
var json = $.parseJSON(j);
console.log(json[0].text); // or alert(json[0].text);
DEMO http://jsfiddle.net/X8GLL/1/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)