2017-03-14 123 views
0

我有這樣一段代碼:爲什麼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');

我該如何解決呢?

+1

放置'location.replace('/ login/index.html');'成功回調的內部。如果您需要特定順序執行某些操作,則需要使用回調函數來定義使用異步函數時的順序,否則運行的順序將取決於異步方法返回所需的時間。請注意'getClients'不等待異步結束;它會立即返回。 – Carcigenicate

+0

@Carcigenicate解決了這個問題! –

回答

0

使用@Carcigenicate建議使用回調解決的問題。

結果代碼是這樣的:

getClients(id, location.replace('/login/index.html')); 

Thak大家的幫助。

0

由於這個過程是動態的,你需要等待Ajax響應,所以我想你可以使用一個裝載機併發送請求到AJAX之前也打電話,如果你的病情沒有在這種情況下隱藏裝載機然後匹配從顯示。

短代碼可以幫助你,

beforeSend:function(){ 
    // init loader here 
}, 
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{ 
     // stop loader here 
相關問題