[英]Seeking more elegant solution to preventDefault() dilemma
我有一個jQuery表單提交例程,該例程在ERROR_CHECK.PHP
中具有輸入完整性檢查,該檢查依賴於傳遞給它的GET
變量進行檢查。 如果傳遞給它的值格式錯誤,則會出現一個警告框,說明錯誤以及應如何糾正表單數據。 將需要彈出此警報框,直到表單數據不再格式錯誤為止,此時該數據將用於重新填充頁面上的數據。
因此,在jQuery例程中,我受我們的朋友preventDefault()
的擺布,並且我找到了一個可行的解決方案,但效果並不理想。 變量allowSubmit
初始化為FALSE
並保持這種方式-並同時生效了preventDefault()
,直到表單數據通過完整性檢查為止,此時allowSubmit
切換為TRUE
...,但這僅在提交正確的代碼后才發生-形成的輸入數據。 這意味着用戶必須提交表單第二秒,以便表單數據可用於替換頁面上的數據...這當然不是解決方案(按兩次提交按鈕?)
但是,通過在將allowSubmit
重置為TRUE
之后立即動態提交表單(在這里,使用$('#my_form').submit() statement)
,我再次提交了表單,從而允許用戶提交格式正確的數據一次,應該從一開始就做。
顯然,這是一個創可貼解決方案,並不優雅。 誰能看到一種更優雅的方式來構造它? (我正在使用由另一位開發人員開發的jQuery,並且這種情況發生在更長的自調用JQuery函數之中,並且我必須按自己的意願使用它,以免不得不重新修改較大部分的所有其他部分。它發生的功能。
這是對代碼的精煉(帶有自描述變量等),它的工作原理與所描述的一樣,盡管不如我所希望的那樣優雅:
var allowSubmit = false;
$('#my_form').on('submit', function(e) {
if (!allowSubmit) {
e.preventDefault();
// Check to see if input data is malformed:
$.get('error_check.php', { new_element_name: $('#new_element_name').val() }, function(data) {
if (data != 0) {
alert("An Error Message that explains what's wrong with the form data");
} else {
allowSubmit = true;
// The line below--an auto-submit--is needed so we don't have to press the submit button TWICE.
// The variable allowSubmit is set to TRUE whenever the submitted form data is good,
// but the code suppressed by e.preventDefault() won't execute until the form is
// submitted a second time...hence the need for this programmatic form submission here.
// This allows the user to correct the errant form data, press the submit button ONCE and continue.
$('#my_form').submit();
}
});
}
$('#element_name').val($('#new_element_name').val());
});
您正在執行的操作還可以,您的其他選擇可能是為通用按鈕編寫一個點擊處理程序,並在驗證后通過該事件提交表單,然后您將需要preventDefault,因為您將不會阻止任何形式的提交動作。 另一個解決方案可能是在驗證后重新觸發事件。
$("button").click(function() {
$("#my_form").submit();
});
...
allowSubmit = true;
// alternatively
jQuery( "body" ).trigger( e );
...
您可以嘗試使用async: false
$.ajax
使用async: false
設置(我不知道您的php返回的是什么,所以我只是在“假裝”它是一個json數組/字符串,如echo json_encode(array("response"=>$trueorfalse));
):
<script>
$('#my_form').on('submit', function(e) {
var valid_is = true;
// Check to see if input data is malformed:
$.ajax({
async: false,
url: 'error_check.php',
type: 'get',
data: { new_element_name: $('#new_element_name').val() },
success: function(response) {
var Valid = JSON.parse(response);
if(Valid.response != true) {
alert("An Error Message that explains what's wrong with the form data");
valid_is = false;
}
}
});
if(!valid_is)
e.preventDefault();
$('#element_name').val($('#new_element_name').val());
});
</script>
如果使用async: false
它將按順序運行腳本,並等待執行腳本的其余部分,直到收到響應為止。 Scott G.說您可以對現有的東西做一些細微的修改,所以我會先嘗試一下。
您擁有的回調解決方案似乎並不合理。 我同意@ scott-g的觀點,通用按鈕單擊事件處理程序可能是最好的選擇。 一種更可測試的方式來編寫您的內容可能是:
var formView = {
$el: $('#my_form'),
$field: $('#element_name'),
$newField: $('#new_element_name'),
$submitBtn: $('#btn-submit')
}
var handleSubmit = function() {
var formData = formView.$field.val();
remoteVerify(formData)
.done(formView.$el.submit)
.done(updateForm)
.fail(handleVerificationError);
};
var remoteVerify = function(formData) {
var deferred = $.Deferred();
var url = 'error_check.php';
var data = { new_element_name: formData };
$.get(url, data)
.done(handleRequest(deferred))
.fail(handleRequestErr);
return deferred;
};
var handleRequest = function(deferred) {
return function (data, jqxhr) {
if (data != 0) {
deferred.reject(jqxhr, "An Error Message that explains what's wrong with the form data");
} else {
deferred.resolve(data);
}
}
};
var handleRequestErr = function() {
// error handling
}
var updateForm = function () {
formView.$field.val(formView.$newField.val());
}
var handleVerificationError = function (jqxhr, errMsg){
alert(errMsg);
}
formView.$submitBtn.on('click', handleSubmit)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.