尝试将从ajax检索到的数组保存到全局变量中,以便我稍后可以使用它,但不断收到未定义的错误
<script>
var items = [];
function add(value){
items.push(value);
}
$(document).ready( function() {
$.ajax({
type: 'POST',
url: 'xxxx.php',
dataType: 'json',
cache: false,
success: function(result) {
for(i=0; i < result.length; i++){
add(result[i]);
}
},
});
});
document.write(items[1])
</script>
最佳答案
这是一个异步 AJAX 调用。对 add
的调用将晚于 document.write(items[1]);
所以这是正确的方法:
<script>
var items = [];
function add(value){
items.push(value);
}
$(document).ready( function() {
$.ajax({
type: 'POST',
url: 'xxxx.php',
dataType: 'json',
cache: false,
success: function(result) {
for(i=0; i < result.length; i++){
add(result[i]);
}
document.write(items[1])
},
});
});
</script>
这样,使用结果的函数将在执行结果函数时执行。
这样想:你说:这是这个柠檬篮子。然后你让某人去某个地方拿柠檬,在他回来之前你试着数柠檬。明白了吗?
关于javascript - Ajax 将数组保存到全局变量中不起作用,一直未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43150243/