简体   繁体   中英

Accessing JSON returned from AJAX object in jQuery

I'm new to jQuery. I'm trying to get some data from MySQL via AJAX. My PHP returns JSON. This is the response (don't mind variables names. It's in Czech :)):

  [{"nadpis":"Testovac\u00ed nadpis","text":"Testovac\u00ed \u010dl\u00e1nek o tom jak se zase prohr\u00e1lo","sestava":"Nikdo nehr\u00e1l"},{"nadpis":"Druhej nadpis","text":"Druhej text","sestava":"druh\u00e1 sestava"}]

Here is my jQuery function:

 $.ajax({ type: 'GET',   
                 url: 'db.php',   
                 datatype:'json',
                 success : function(data)
                 {  console.log(data[1].text);
                    console.log(data);
                 }
        });

The problem is that when I want to access data[1].text, it only returns undefined . I went through a lot of answers here on StackOverflow and other forums, but I still can't make it work.

Change data t ype to data T ype . Otherwise jQuery doesn't recognize the option and won't parse the response for you.

In your case, data is still a string, which you can verify with console.log(typeof data) . data[1] returns "{" , and "{".text is undefined .

Have a look at the documentation for the correct option names: http://api.jquery.com/jquery.ajax/


Alternatively, you could parse the response yourself .

(I posted an answer to prevent other misguiding answers. It's community wiki because I voted to close the question.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM