我正在使用jQuery-step库和一个组合formvalidation.js的表单。我想延迟低于方法响应,直到ajax完成。
我希望在ajax完成时发送返回 true / false 。
onStepChanging: function (e, currentIndex, newIndex) {
var fv = $stepForm.data('formValidation'), // FormValidation instance
// The current step container
$container = $stepForm.find('section[data-step="' + currentIndex + '"]');
// Validate the container
fv.validateContainer($container);
var isValidStep = fv.isValidContainer($container);
if (isValidStep === false || isValidStep === null) {
// Do not jump to the next step
return false;
}
if (isValidStep === true) {
//call ajax here
//wait for ajax to complete then move to next or keep
}
return true; //-> i want to delay this
},
答案 0 :(得分:0)
我通过在javascript window
中设置属性然后在setTimeout函数中包装返回来完成
第1步:
$(document).ready(function(){ window.flag = ''; });
第2步
function submitForm($stepForm) {
$.ajax({
type: 'POST',
url: 'http://' + location.host + "/ajax",
dataType: 'JSON',
data: {'method': 'submitApplication', 'formdata': $stepForm.serialize()},
success: function (data) {
window.flag = true;
}
}
第3步:
onStepChanging: function (e, currentIndex, newIndex) {
if (isValidStep === true) {
submitForm($stepForm);
}
.... code
setTimeout(function () {
return window.flag;
}, 2000);
}
答案 1 :(得分:0)
在你的情况下:
function submitForm($stepForm) {
return new Promise((resolve, reject) =>{
$.ajax({
type: 'POST',
url: 'http://' + location.host + "/ajax",
dataType: 'JSON',
data: {'method': 'submitApplication', 'formdata': $stepForm.serialize()},
/* Resolving true on success, you could also return a json object if you need the response */
success: () => { resolve(true); },
/* Rejecting the promise in case of an error */
error: () => { reject(false) }
})
})
}
然后:
onStepChanging: function (e, currentIndex, newIndex) {
if (isValidStep === true) {
submitForm($stepForm)
.then( /*...Do whatever you want ..*/)
.catch( console.log );
}