访问JSON不起作用 [英] Accessing json does not work

查看:154
本文介绍了访问JSON不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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

这篇关于访问JSON不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆