Accessing json does not work

后端 未结 3 1510
臣服心动
臣服心动 2021-01-28 22:32

I am using Ajax to receive a JSON update:

    $(document).ready(function(){
    $(\'form\').submit(function(event){
        event.preventDefault();
        var f         


        
相关标签:
3条回答
  • 2021-01-28 23:31

    set the dataType to json so that the response is parsed

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

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

    0 讨论(0)
  • 2021-01-28 23:34

    JavaScript arrays start at 0, not 1.

    0 讨论(0)
  • 2021-01-28 23:35

    Your array only has one element, so you want to use 0 as your index:

    alert(data[0].text);
    
    0 讨论(0)
提交回复
热议问题