我有这段代码:
data = new FormData($('#form')[0]);
$.ajax({
type: 'POST',
url: 'systems/createpostsystem.php',
data: data,
cache: false,
contentType: false,
processData: false
}).done(function(data) {
alert(data);
window.location = "myposts.php";
});
我用过$.ajaxStart()
,但它没有做我想要的。
我也尝试了success:function(){my code}
并提出了两次我的要求!
现在我想在此 AJax 完成时显示进度图像。
在执行 ajax 函数之前添加加载图像(我假设是 gif)。成功后,删除图像并将其替换为您想要的任何内容(成功图像、从服务器返回的数据等)。
例:
var formData = new FormData($('#form')[0]);
var imageContainer = $('#selector');
imageContainer.attr('src', 'path/to/loading.gif');
$.ajax({
type: 'POST',
url: 'systems/createpostsystem.php',
data: formData,
success: function(data) {
// Do something
}
});
JavaScriptajaxjquerydom
您只需要在执行 AJAX 请求之前编辑 DOM,添加加载器,然后在complete
回调中删除它。我通常使用 jQuery 回调函数而不是 XHR 对象回调。
请注意:
- 仅当请求成功完成时,才会调用
success
回调(和done
XHR 回调)
即使 - 请求失败,也始终调用
complete
(以及always
XHR 回调)。
例:
function addLoader() {
var img = $('<img />', {
id: 'loader',
src: '/path/to/your/loader.gif'
});
img.appendTo($('body'));
}
function removeLoader() {
$('#loader').remove();
}
addLoader(); // here the we add our loader
data = new FormData($('#form')[0]);
$.ajax({
type: 'POST',
url: 'systems/createpostsystem.php',
data: data,
cache: false,
contentType: false,
processData: false,
complete: function() {
removeLoader(); // here we remove it
},
success: function(data) {
alert(data);
window.location = "myposts.php";
}
});