Thursday, 28 September 2017

javascript - Get array value from AJAX request




I have a script that reads a JSON file then populates an array with the name property of each element.



HTML







JSON



[
{"name" : "One"},
{"name" : "Two"},
{"name" : "Three"},
{"name" : "Four"},
{"name" : "Five"}
]


I cant't access a specific index of this array. The console log always returns undefined. I've tried to add .then() after my ajax call, but it doesn't work too.


Answer



You'll wanna do something like this:







Javascript won't wait for all of your code to run line by line, so for asynchronous calls you'll need a seperate function to handle data OR to handle the data within the success callback. Another function would be cleaner though depending on what you want to do with the data.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...