ajaxでの同期と非同期の違いと使用シーンを深く理解する
3607 ワード
まず2つのコードを行って、この2つのコードのconsoleを当てます.logの実行順序と結果:
コード1:
コード2:
コード1:
$.ajax({
type: "post",
async:true, // true
url: "/teacher/ajaxtimeline",
data: {"month": month, "uid":uid);?>},
dataType: "json",
success: function(data) {
// data.canNotSetDays [9,10,11]
$.each(data.canNotSetDays, function(i, item) {
canNotSetDays.push(item);
});
console.log('**********ajax result ************');
// canNotSetDays , 9
console.log(canNotSetDays);
console.log(canNotSetDays.length);
console.log(canNotSetDays.indexOf(9));
}
});
console.log('***********after ajax ***********');
// canNotSetDays , 0, 9
console.log(canNotSetDays);
console.log(canNotSetDays.length);
console.log(canNotSetDays.indexOf(9));
console.log('**********delay two seconds************');
setTimeout(function(){
// 2 canNotSetDays , 9
console.log(canNotSetDays);
console.log(canNotSetDays.length);
console.log(canNotSetDays.indexOf(9));
}, 2000);
コード2:
$.ajax({
type: "post",
async:false, // true
url: "/teacher/ajaxtimeline",
data: {"month": month, "uid":uid);?>},
dataType: "json",
success: function(data) {
// data.canNotSetDays [9,10,11]
$.each(data.canNotSetDays, function(i, item) {
canNotSetDays.push(item);
});
console.log('**********ajax result ************');
// canNotSetDays , 9
console.log(canNotSetDays);
console.log(canNotSetDays.length);
console.log(canNotSetDays.indexOf(9));
}
});
console.log('***********after ajax ***********');
// canNotSetDays , 9
console.log(canNotSetDays);
console.log(canNotSetDays.length);
console.log(canNotSetDays.indexOf(9));
console.log('**********delay two seconds************');
setTimeout(function(){
// 2 canNotSetDays , 9
console.log(canNotSetDays);
console.log(canNotSetDays.length);
console.log(canNotSetDays.indexOf(9));
}, 2000);