ajax中async同步和非同步的區別和使用技巧
而非同步則這個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,所以後面就好理解了。