Lex*_*exx 1 javascript arrays ajax jquery json
我正在尝试获取json数据$.getJSON并且它工作正常.这是我的代码:
$(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>");
});
Run Code Online (Sandbox Code Playgroud)
我正在尝试将它分配给数组供以后使用,但是当我尝试访问它并显示它时,我得到了undefined.
我肯定得到了所有的数据,但是当我分配它时,MainArray我无法在$.each函数外部访问它,我不知道为什么.
那是因为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>");
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
946 次 |
| 最近记录: |