2015-11-17 91 views
0

這裏是我的代碼:重定向用戶收到

$.ajax({ 
    type: "POST", 
    url: "/script.php", 
    data: { "action" : "importData" }, 
    cache: false, 
    async: true, 
    success: function() { 
     window.location.href = "/next-page"; 
    } 
}); 

在此頁面上的用戶土地,阿賈克斯將觸發PHP腳本,大約需要15秒鐘才能完成。與其讓用戶等待腳本完成並重定向腳本,我想獲得某種類型的腳本已被觸發的確認,然後重定向用戶而無需等待整個腳本完成。該工作流程的許多分鐘後纔會使用該腳本的結果。

這可能嗎?如何做?

+0

默認情況下它不會等待,只需將重定向到一個呼叫(從成功刪除) –

回答

0

$.ajax()返回XMLHttpRequest實例:

var xhr = $.ajax({ 
    type: 'POST', 
    url: '/script.php', 
    data: {action: 'importData'}, 
    cache: false, 
    success: function(){ 
    location = '/next-page'; 
    } 
}); 
/* to test if problem is jQuery remove this line and take comments out 
var px = xhr.onreadystatechange; 
*/ 
xhr.onreadystatechange = function(){ 
    //if(px)px(); 
    if(xhr.readyState === 3 && xhr.status === 200){ // look at Properties -> https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest 
    // do stuff here with xhr.readyState less than 4 
    } 
} 

有效XMLHttpRequest.readyState屬性值可以發現here

請注意,如果您重定向用戶,JavaScript的當前頁面上停止。用戶重定向到的頁面可能有自己的JavaScript。

+0

xhr.onreadystatechange不會被調用,因此我window.location.href =「/下頁」後;在那裏如果陳述沒有被執行? – TimNguyenBSM

+0

'xhr.onreadystatechange'時自動調用了'的'XMLHttpRequest'在你的情況下的具體實例,'xhr' readyState'變化。 ''.ajax({})'內的'success'方法在'xhr.readyState === 4 && xhr.status === 200)'時觸發''。如果'success'沒有執行,則可能是因爲你的代碼的'xhr.onreadystatechange'函數內發生的事情在做一些事情,以防止它,或者'jQuery'使用相同的分配方法,我這樣做,而不是'xhr.addEventListener' 。如果它是'jQuery'問題,我有解決方案。 – PHPglue