在使用異步請求時,有時需要將異步請求的結果返回給另一個js函數,此種情況下會出現未等異步請求返回請求結果,該發送請求所在js函數已經執行完后續操作,即已經執行return ,這樣會導致return的結果為空字符。
總結:若要在使用ajax請求后處理發送請求返回的結果,最好使用同步請求。
例如:以下例子會出現返回結果不正確的情況,因為ajax異步請求還未執行完,函數已經執行return了,
function fn(){
var result = " ";
$.ajax({
url : 'your url',
data:{name:value},
cache : false,
async : true,
type : "POST",
success : function (data){
do something....
result = ....
}
// 對ajax中返回的data進行處理 ,也會出錯
return result ;
}
1 異步請求方式:
$.ajax({
url : 'your url',
data:{name:value},
cache : false,
async : true,
type : "POST",
dataType : 'json/xml/html',
success : function (result){
do something....
}
});
2 同步請求方式
$.ajax({
url : 'your url',
data:{name:value},
cache : false,
async : false,
type : "POST",
dataType : 'json/xml/html',
success : function (result){
do something....
}
});