简体   繁体   English

Javascript数组访问外部函数

[英]Javascript array access outside function

I'm trying to get json data with $.getJSON and it's working fine. 我正在尝试使用$.getJSON获取json数据,并且工作正常。 This is my code: 这是我的代码:

$(document).ready(function(){
    var MainArray = new Array();
    $.getJSON('check-location.php?onload=true', function(result) {
        $.each(result, function(i){
            MainArray[i] = result[i].CountryName;
        });
    });

    $(".drop-down").append("<div>" + MainArray[0] + "</div>");
});

I'm trying to assign it to array for later usage, but when I try to access it and display it I get undefined . 我正在尝试将其分配给数组以供以后使用,但是当我尝试访问并显示它时,我会得到undefined

I get all the data for sure, but when I assign it to MainArray I cant access it outside the $.each function and I've no idea why. 我可以肯定地获得所有数据,但是当我将其分配给MainArray我无法在$.each函数外部访问它,我也不知道为什么。

That's because Ajax is asynchronous , you are trying to append a non-existent value: 这是因为Ajax是异步的 ,您试图附加不存在的值:

$.getJSON('check-location.php?onload=true', function(result) {
    $.each(result, function(i){
        MainArray[i] = result[i].CountryName;
    });
    $(".drop-down").append("<div>" + MainArray[0] + "</div>");
});

Because $.getJSON is asynchronous, the MainArray isn't updated until the data is successfully returned. 由于$.getJSON是异步的,因此在成功返回数据之前,不会更新MainArray

But, the line 但是,线

$(".drop-down").append("<div>" + MainArray[0] + "</div>");

will have already executed before the $.getJSON is completed...hence it is undefined . $.getJSON完成之前将已经执行...因此undefined

You should move this somewhere and execute it when your data has returned, ie. 您应该将其移动到某个地方并在返回数据后执行它,即。 in the callback 在回调中

Like every body said, because its an asynchronous request you can turn that off (not a very good practice, but it will fix the problem) 就像每个人都说的那样,因为它是异步请求,所以您可以将其关闭(这不是很好的做法,但可以解决问题)

Add this before the $.getJSON call 在$ .getJSON调用之前添加它

$.ajax({ async: "false" }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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