Below is my code in a JavaScript file that is included in an HTML file. When I console.log msg I can see there are 100 items in the array (see screenshot), however dataArray is still empty after the last console.log(dataArray).
I don't get any errors or things like that so it's hard for me to debug this.
function loadPosts() {
var dataArray = new Array();
var root = 'https://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/',
method: 'GET',
success:function(msg){
dataArray = msg;
}
});
console.log(dataArray);
}
window.onload = loadPosts;
答案 0 :(得分:3)
在调用AJAX请求的成功处理程序之前,您的console.log
已执行,否则它看起来是正确的。在回调中指定console.log(dataArray)
后,您可以添加dataArray = msg;
以查看它。
答案 1 :(得分:2)
AJAX本质上是异步的,所以正在执行的是:
对于所需的输出,您应该将控制台日志移动到成功处理程序中:
function loadPosts() {
var dataArray = new Array();
var root = 'https://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/',
method: 'GET',
success:function(msg){
dataArray = msg;
// act on data array
console.log(dataArray);
}
});
}
我还建议从成功/错误回调转移到Promises
,因为从jQuery 3开始不推荐使用回调并删除它。这会改变你的代码:
function loadPosts() {
var root = 'https://jsonplaceholder.typicode.com';
return $.ajax({
url: root + '/posts/',
method: 'GET'
});
}
loadPosts().then(function(data) {
// resolve promise handler
// do something with your data
console.log(data);
}, function(err) {
// rejected promise handler (failure)
console.error(data);
});
欲了解更多信息:
答案 2 :(得分:1)
请检查以下代码:
function loadPosts() {
var dataArray = [];
var root = 'https://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/',
method: 'GET',
success:function(msg){
console.log('First');
dataArray = msg;
}
});
console.log('Second');
console.log(dataArray);
}
window.onload = loadPosts;

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
你会看到执行的顺序。 如果你需要在他的赋值后处理dataArray,那么在成功回调时,你需要调用一个函数并将新的dataArray作为参数传递。
答案 3 :(得分:0)
var time =0;
var player = document.getElementById('player');
player.addEventListener('timeupdate',function(e){
time = e.target.currentTime;
},false);
var doOnce = function(){
console.log('do something once');
};
function loop(){
//update and draw animation
//execute doOnce when player.currentTime >= 10
if( doOnce && time >= 10 ){
//is this bad practice?
doOnce = doOnce();
}
setTimeout(loop,32);
}
loop();
player.play();