Here's my code:
$(document).ready(function() {
var myArray = [];
$.getJSON("some url",function(data){
$.each(data, function(){
myArray.push("a string" + this);
});
alert(myArray);
});
//alert(myArray);
});
The code as shown is working just fine and it displays the array and its contents.
However, when I try to display the array by having the command line right after the $.each
code block (commented out in the sample code), the array and its contents are not displayed. An empty/ blank message is returned instead.
Why is this happening and how can I fix it? I'd like to have the command " alert(myArray);
" right after the $.each
block.
Thank you in advance!
var myArray = [];
var jqxhr = $.getJSON( "some url", function(data) {
$.each(data, function(){
myArray.push("a string" + this);
});
}) ;
jqxhr.complete(function() {
console.log(myArray);
});
jQuery XHR object, or "jqXHR," is returned by $.getJSON()
When the request is already complete, the .complete() callback is fired immediately.
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.