如何在步骤向导中不断对多个窗体进行 ajax 调用



我正在使用插件来创建向导(步骤(。目前,我需要在每个步骤上发送一个ajax调用(离开步骤时(。我遇到了一个问题,它一直在发送无限的 ajax 调用,所以我内置了一个检查是否已经进行了 ajax 调用,但现在它不会在第一步之后发送任何 ajax 调用。

我该如何改变它?

这是我的代码:

var ajaxInvoke = false;
$("#smartwizard").on("leaveStep", function(e, anchorObject, stepNumber, stepDirection) {
if(ajaxInvoke == false){
ajaxInvoke = true;
var form_data = $("#step_"+ stepNumber +"_form").serialize();
$.ajax({
type:'post',
url:"catalog/calcdiv.php",
data:form_data,
success:function(data){
// indicate the ajax has been done, release the next step
$("#smartwizard").smartWizard("next");
}
});
// Return false to cancel the `leaveStep` event
return false;
}
});

这是我的 html:

<div id="step-0" class="">
<form id="step_0_form" method="post">
<input type="number" class="formateninput form-control" name="aantal" value="1" min="1">
</form>
</div>
<div id="step-1" class="">
<form id="step_2_form" method="post">
<input type="number" class="formateninput form-control" name="hoogte" value="100" min="60">
</form>
</div>
<div id="step-2" class="">
<form id="step_3_form" method="post">
<input type="radio" id="Hout" name="Materiaal" value="Hout" >
<input type="radio" id="Debond" name="Materiaal" value="Debond">
</form>
</div>

我可以在我的网络选项卡中看到它发布了第一步,但是当单击下一步时,第一个之后不再有 ajax 调用。

你应该重置你设置的布尔标志,也许是这样的:

$.ajax({
type:'post',
url:"catalog/calcdiv.php",
data:form_data,
success:function(data){
// indicate the ajax has been done, release the next step
$("#smartwizard").smartWizard("next");
},
complete: function(){ ajaxInvoke = false; }
});

这样,当 ajax 完成、失败或成功时,变量将被重置,下一个 ajax 将能够发送。

变量与您分配的值相同(ajaxInvoke = true( 如果要在代码中使用变量;

var ajaxInvoke = false;
$("#smartwizard").on("leaveStep", function(e, anchorObject, stepNumber, stepDirection) {
if(ajaxInvoke == false){
ajaxInvoke = true;
var form_data = $("#step_"+ stepNumber +"_form").serialize();
$.ajax({
type:'post',
url:"catalog/calcdiv.php",
data:form_data,
success:function(data){
// indicate the ajax has been done, release the next step
ajaxInvoke = false;
$("#smartwizard").smartWizard("next");
}
});
// Return false to cancel the `leaveStep` event
return false;
}
});

除了重置其他用户提到的变量外,请检查事件被触发的时间和次数,还尝试使用事件函数推送单个对象:

var ajaxInvoke = false;
var evtOptions = {
'anchorObject' : anchorObject,
'stepNumber' : stepNumber,
'stepDirection' : stepDirection
}
$("#smartwizard").off("leaveStep");
$("#smartwizard").on("leaveStep", function(e, evtOptions) {
if(ajaxInvoke == false){
ajaxInvoke = true;
var form_data = $("#step_"+ evtOptions.stepNumber +"_form").serialize();
$.ajax({
type:'post',
url:"catalog/calcdiv.php",
data:form_data,
success:function(data){
// indicate the ajax has been done, release the next step
ajaxInvoke = false;
$("#smartwizard").smartWizard("next");
}
});
// Return false to cancel the `leaveStep` event
return false;
}
});

也只是作为一般的工作实践, 我建议使用$(document)作为事件总线,因为使用页面元素有时会带来奇怪的边缘情况

此外,在设置事件侦听器时,请始终将其删除并$().off()以避免复杂化

最新更新