在網上看了很多關於ajax中同步和異步的區別,這個同步的意思是當JS代碼加載到當前AJAX的時候會把頁面里所有的代碼停止加載,頁面出去假死狀態,當這個AJAX執 行完畢后才會繼續運行其他代碼頁面假死狀態解除。
而異步則這個AJAX代碼運行中的時候其他代碼一樣可以運行。
下面貼上一段代碼進行分析。
function createTable(){
var data = getAllLocation(); //調用getAllLocation()函數
var locationList = data.locationList; 這的data.locationList中的locationList是后台中的,是位置的集合。
if(locationList.length<=0){
$('#noData').css("display","block");
}else{
$('#noData').css("display","none");
$.each(locationList, function(i) {
$('#tagTable tbody').append('<tr>');
$('#tagTable tbody').append('<td title="" valign="top" nowrap><input csaId="'+this.id+'" type="checkbox" value="" /></td>');
$('#tagTable tbody').append('<td title="'+this.engineRoom+'" nowrap>'+this.engineRoom+'</td>');
$('#tagTable tbody').append('<td title="'+this.cabinet+'" nowrap>'+this.cabinet+'</td>');
$('#tagTable tbody').append('</tr>');
});
}
}
//獲取位置信息
function getAllLocation(){
var dataJson = null;
$.ajax({
type:'POST',
async:false,
dataType:'json',
url:'getAllLocation',
success:function(data){
dataJson = data;
}
});
return dataJson;
}
通過上面的代碼,如果async:false表示同步,這時頁面處於假死狀態,ajax后面的代碼不會去執行。程序運行不會出現問題。
當把async中的false改成true時,運行會報錯。
因為,直接執行了代碼returna dataJson,所以后面就好理解了。
