[英]How to prevent form from submitting with AJAX validation
當我使用ajax進行驗證時,如何防止表單提交。 問題在於ajax是異步的,實際結果(在我的情況下為false
)稍后會出現。 使Ajax
sync
是正確的方法嗎? 這是我的代碼:
$('#w0').on('beforeSubmit', function(e){
let loadDate = $('#dstrequest-load_date').val()
let shippingDate = $('#dstrequest-shipping_date').val()
let requestId = '".($model->isNewRecord ? 0 : $model->id)."'
let trucks = $('.container-items_truck').find('.truck-item')
let ids = []
let result = true
$.each(trucks, function(){
let id = $(this).find('select').first().val()
if(ids.indexOf(id) === -1)
ids.push(id)
})
$.ajax({
method: 'post',
url: '/erp/distribution/dst-vehicle/check-truck-engage-date',
data: {
load_date: loadDate,
shipping_date: shippingDate,
trucks: ids,
request_id: requestId
}
})
.done(function(data){
let selects = $('select[name$=\"[truck_id]\"]')
$.each(selects, function(){
let val = $(this).val()
if(data.indexOf(val) !== -1){
$('#w0').yiiActiveForm('updateAttribute', $(this).attr('id'), ['".Yii::t('distribution', 'distributionCore.busy_truck')."'])
result = false
}
})
})
.always(function(data){
let transfer_wrapper = $('.transfer-wrapper')
$.each(transfer_wrapper, function(){
if($(this).is(':visible')){
let fields = $(this).find('input, select')
$.each(fields, function(){
if($(this).val() == ''){
let id = $(this).attr('id')
$('#w0').yiiActiveForm('updateAttribute', id, ['" . Yii::t('distribution', 'distributionCore.please_fill_the_field') . "'])
result = false
}
})
}
})
})
// HERE THE RESULT SHOULD BE FALSE BECAUSE OF THE AJAX VALIDATION BUT IT'S TRUE BECAUSE OF THE ASYNC BEHAVIOUR.
return result
})
使Ajax同步是正確的方法嗎?
否。不推薦使用來自JS的同步HTTP請求。 切勿使用它們。
您需要:
始終禁止提交普通表單。
驗證輸入后,使用Ajax,使用JS重新提交表單(無需重復驗證)。
輸入數據時,逐字段進行驗證。
希望在最后一個字段完成並提交表單之前,Ajax將完成。
到那時,如果Ajax 還沒有完成,您要么不得不冒險提交表單,要么不知道Ajax驗證的結果,或者退回到我建議的第一個選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.