gpt4 book ai didi

javascript - ajax/jQuery 中 done 函数的相反函数

转载 作者:行者123 更新时间:2023-11-29 14:52:48 24 4
gpt4 key购买 nike

我想使用 jQuery 通过 Ajax 发送表单。

提交表单时,数据传输中会显示加载图像。

在纯 JS 中我使用了这段代码:

var myForm = document.getElementById('myForm');
var xhr = new XMLHttpRequest();

myForm.addEventListener('submit', function(e){
var formData = new FormData(myForm);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200) {
loading.style = "visibility:hidden;";
alert('Authentification réussi.\n' + xhr.responseText );
}else{
loading.style = "visibility:visible;";
}
};
xhr.open("GET", "authentification.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(formData);
e.preventDefault();
}, false);

这就是我使用 jQuery 尝试的结果:

var jqxhr = $.ajax({
type : $('#myForm').attr('method'),
url : $('#myForm').attr('action'),
data : $('#myForm').serialize(),
dataType : 'html'
});


$(function(){
$('#myForm').submit(function(event){
jqxhr.done(function(data){
$('#loading').hide();
alert(data);
});
//Here the other method
});
event.preventDefault();
});

问题是我不知道发送数据时将执行的函数是什么,在纯 JS 中我只是使用 else 语句:xhr.readyState == 4 && xhr.status == 200.

那么,负责它的函数是什么?

编辑:

解决方案是使用属性 beforeSend 如下:

jqxhr = $.ajax({
type : $(this).attr('method'),
url : $(this).attr('action'),
data : $(this).serialize(),
dataType : 'html',
beforeSend : function(){
$('#loading').show();
},
complete : function(){
$('#loading').hide();
}
})

最佳答案

您需要在提交处理程序中发送 ajax 请求...当您说 $.ajax(..) 时,ajax 请求已发送,因为您已将代码放在全局上下文中this 指的是窗口对象。

var jqxhr;
$(function () {
$('#myForm').submit(function (event) {
jqxhr = $.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'html'
}).done(function (data) {
$('#loading').hide();
alert(data);
}).always(function () {
jqxhr = undefined;
});
//Here the other method
});
event.preventDefault();
});

关于javascript - ajax/jQuery 中 done 函数的相反函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22744243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com