在使用異步請求時,有時需要將異步請求的結(jié)果返回給另一個js函數(shù),此種情況下會出現(xiàn)未等異步請求返回請求結(jié)果,該發(fā)送請求所在js函數(shù)已經(jīng)執(zhí)行完后續(xù)操作,即已經(jīng)執(zhí)行return ,這樣會導(dǎo)致return的結(jié)果為空字符。
總結(jié):若要在使用ajax請求后處理發(fā)送請求返回的結(jié)果,最好使用同步請求。
例如:以下例子會出現(xiàn)返回結(jié)果不正確的情況,因為ajax異步請求還未執(zhí)行完,函數(shù)已經(jīng)執(zhí)行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進(jìn)行處理 ,也會出錯
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....
}
});