嘗試類似這樣的事情。這是你的HTML:
<form action="upload.php" method="post" enctype="multipart/form-data" id="UploadForm">
<button type="submit" value="submit" id="SubmitButton">Submit</button>
<button type="button" id="CancelButton" disabled>Cancel</button>
</form>
這是你的jQuery和JavaScript:
$(function() {
var $form = $('#UploadForm');
var form = $form.get(0);
var $submit = $('#SubmitButton');
var $cancel = $('#CancelButton');
var xhr = null;
function cleanup() {
xhr = null;
$submit.removeAttr('disabled');
$cancel.attr('disabled', true);
}
function doneCallback() {
// your code for completed form submission goes here
// redirect the page or whatever you need to do
cleanup();
}
$cancel.on('click', function() {
if($cancel.attr('disabled')) {
return;
}
if(xhr instanceof XMLHttpRequest) {
xhr.abort();
}
cleanup();
})
$form.on('submit', function(event) {
event.preventDefault();
xhr = new XMLHttpRequest();
xhr.open($form.attr('method'), $form.attr('action'), true);
xhr.addEventListener('load', doneCallback);
$submit.attr('disabled', true);
$cancel.removeAttr('disabled');
xhr.send(new FormData(form));
return false;
});
});
它使用FormData
API,以便檢查browser support for that。
使用'event.preventDefult();'所以很多時候問。 –
@Parth Trivedi ...我懷疑event.preventDefault是否會在這種情況下工作。一旦點擊提交按鈕,表單將被髮布,如何防止默認停止在中途? –
你可以有一個'click'處理程序,根據條件,你可以'返回false',它應該停止。 – Rajesh