Wednesday, 2 March 2016

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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...