我的全局JavaScript变量只增加到0
为什么?
我正在使用此代码
同一页
<?php $array = array('apple','banana','mango'); ?>
<script type="text/javascript">
var my_delay = 1500; // 60000 millisecond = 1 minute
var globalIndex = -1;
var collectedArray = <?php echo json_encode($array); ?>;
function callItself() {
$.ajax({
url: ....
success: function(data) {
globalIndex = globalIndex + 1;
console.log(globalIndex); // prints 0, 1, 2
console.log(collectedArray[globalIndex]) // prints apple,undefined,undefined
setTimeout(function() {
console.log('finished this operation');
callItself();
}, my_delay);
} // end of success
});
} // end of callItself
</script>
我的问题:
我得到了console.log(globalIndex); // prints 0 , 1, 2
但对于此console.log(collectedArray[globalIndex]) // prints apple,undefined,undefined
为什么我得到2 undefined
答案 0 :(得分:1)
除非强制ajax调用与async: false
同步,否则不要直接更新success函数中的变量。一个好主意是将计算移动到回调函数而不是强制ajax同步:
<script type="text/javascript">
var my_delay = 150; // 60000 millisecond = 1 minute
var globalIndex = -1;
var collectedArray = <?php echo json_encode($array); ?>;
function callItself() {
$.ajax({
url: 'json.php',
success: function(data) {
mycallback()
} // end of success
});
} // end of callItself
function mycallback(){
globalIndex = globalIndex + 1;
console.log(globalIndex);
console.log(collectedArray[globalIndex]);
setTimeout(function() {
console.log('finished this operation');
callItself();
}, my_delay);
}
</script>