我有這樣一段代碼:爲什麼location.replace()在AJAX請求仍在運行時執行?
getClients(id);
location.replace('/login/index.html');
getClients()
我功能基本上是一個ASYCAJAX
請求。
如果客戶端列表爲空,它將重定向到另一個頁面。下面是Ajax請求裏面的代碼:
....
success: function(data){
var json2 = $.parseJSON(JSON.stringify(data.result));
$.cookie('usu', id, {path: '/'});
if(json2.length < 2 && json2[0].UserClients.length === 0){
location.replace('/login/user_config.html');
return false;
}
else{
....
但不知何故,如果客戶對象爲空,則執行location.replace('/login/index.html');
,然後再執行location.replace('/login/user_config.html');
我該如何解決呢?
放置'location.replace('/ login/index.html');'成功回調的內部。如果您需要特定順序執行某些操作,則需要使用回調函數來定義使用異步函數時的順序,否則運行的順序將取決於異步方法返回所需的時間。請注意'getClients'不等待異步結束;它會立即返回。 – Carcigenicate
@Carcigenicate解決了這個問題! –