访问JSON不起作用不起作用、JSON

2023-09-10 15:46:47 作者:悄無聲息沉迷

我使用Ajax来获得JSON更新:

I am using Ajax to receive a JSON update:

    $(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-对象看起来是这样的:

Now comes the bad the receiving JSON-Object looks like this:

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

和我现在要与访问文本:

and when I now want to access the text with:

alert(data[1].text);

我得到了一个未定义....

I get undefined....

我是什么做错了吗?

最好的问候, 博德

推荐答案

设置的dataType JSON 使响应被分析

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

或手动解析JSON

or manually parse the 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