我想通過Ajax
發送表單,其中jQuery
。ajax/jQuery中完成功能的相反功能
提交表單後,會在數據傳輸中顯示加載圖像。
在純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();
}
})
for'$(this)'我忘了修改它,我用'$('#myForm')'insted。我在提交處理程序中使用了'.ajax(..)',但是我需要中止另一個處理程序的'Ajax'查詢,所以我需要在全局聲明它。 –
@AimadMAJDOU在這種情況下,只聲明全局變量,並在調用中止前檢查值是否未定義,如'if(jqxhr!= undefined){jqxhr.abort()}'(見更新) –
爲什麼'jqxhr'全球? – Bergi