[英]How to display a progress bar during an ajax request (jquery/php)
我有一個ajax請求,據此我將自動安裝一個magento商店,當該過程完成后,它將把用戶重定向到新創建的商店。 這是我的代碼:
function postSuccessFormData() {
var targetUrl = '/index.php/install/wizard/successPost';
jQuery('.form-button').addClass('loading');
setInterval(installStatus(),4000);
jQuery.ajax({
url: targetUrl,
global: false,
type: 'POST',
data: ({
finish: 1,
password_key: jQuery('#password_key').val()
}),
async: true,
dataType: 'json',
error: function() {
alert("An error has occurred. Please try again.");
},
success: function(data) {
window.location.href = '/';
}
});
function installStatus() {
var installerUpdatesUrl = '/index.php/install/wizard/installerStatus';
//showProgressBar();
jQuery.ajax({
url: installerUpdatesUrl,
// global: false,
type: 'GET',
async: true,
dataType: 'json',
error: function (data) {
// alert(data.result);
},
success: function (data) {
handle data.result
var dataKeys = Object.keys(data);
var lastElementKey = dataKeys[dataKeys.length - 1];
var lastMessage = data[lastElementKey]['message'];
if(data[lastElementKey]['progress'] == '') {
updateProgressBar(data[dataKeys[dataKeys.length - 2]]['progress'],100);
}
setting message
jQuery("#message").html(lastMessage);
if (data[lastElementKey]['state'] == 'Failure') {
var stepStr = lastElementKey.split('_');
var stepString = stepStr[0].toUpperCase() + ' ' + stepStr[1] + ':';
alert(stepString + "\n" + data[lastElementKey]['message']);
//hideProgressBar();
jQuery('.form-button').removeClass('loading');
return false;
} else if (data[lastElementKey]['state'] == 'Finish') {
alert(data[lastElementKey]['message']);
//hideProgressBar();
jQuery('.form-button').removeClass('loading');
//window.location.href = '/';
} else {
// installStatus();
}
},
complete: function () {
installStatus();
jQuery('.form-button').removeClass('loading');
}
});
}
完成的方式:
每隔4秒鍾運行一次功能installStatus,它將以JSON格式輸出當前進度。 我的問題是,此函數需要與函數post()同時執行。
這沒有發生,僅在第一個功能完成后才運行installStatus。
怎么了?
定義時,您正在執行installStatus
。 所以這:
setInterval(installStatus(),4000);
需要是
setInterval(installStatus, 4000);
新的XMLHttpRequest有一個不錯的progress
事件,您可以收聽以向用戶顯示上傳進度。
這是帶有一個不錯的演示的規范: https : //developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress
最初,您應該只調用一次installStatus(),然后在ajax成功內的方法內部,應在進度欄中更新procent,然后遞歸調用相同的方法。 在服務器端,您可以將當前procent保存在cookie中,並且通過每次遞歸調用,您都可以更新cookie並返回procent。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.