Friday, September 28, 2018

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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...