假设我的网页中有一个文本框,并且我已经使用jQuery在此文本框上附加了“更改”事件。
$('.myFormClass').on('change', '.amount', function () {
// Some AJAX call here, and the response is assigned to a variable
});
我也有一个表单提交事件,
$('.myFormClass').on('submit', 'form', function (e) {
// some code in which I use the response from the earlier AJAX call returned against 'change' event
});
问题是'change'事件可以单独正常工作,但是提交表单时,它们几乎同时被触发,直到AJAX调用'change'事件的调用被返回(假设是)时,表单已经提交到那时,所以我不能使用AJAX响应,这是在提交表单之前需要的。
在这种情况下是否有内置的jQuery?如果没有,还有其他有效的解决方案吗?
答案 0 :(得分:0)
添加一个按钮。当用户单击按钮时,布尔值设置为tru,如果为true,则仅会提交,否则只有onchange函数起作用,而不是Submit函数。
var sub=false;
$(document).ready(function(){
$('button').click(function(){sub=true;console.log(sub)})
$('.myFormClass').on('change', '.amount', function () {
// Some AJAX call here, and the response is assigned to a variable
console.log('changed')
});
$('.myFormClass').keypress((e)=>{if(e.keyCode=='13'){e.preventDefault();console.log('not submitted on enter')}})
$('.myFormClass').click( function (e) {
e.preventDefault();
console.log("submit cancelled")
if(sub)
$(this).submit();
// some code in which I use the response from the earlier AJAX call returned against 'change' event
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="myFormClass">
aa
<input class="amount">
<input type="submit">
</form>
<button>Want to submit the form?</button>
答案 1 :(得分:0)
存储ajax承诺并在表单提交处理程序中等待其解决
let amountReady = null;
$('.testForm').on('change', '.amount', function(ev) {
amountReady = $.ajax({
method: 'POST',
url: 'https://httpbin.org/post',
data: {
amount: $(this).val()
}
});
});
$('.testForm').on('submit', 'form', function(e) {
e.preventDefault();
if (!amountReady) return;
amountReady.then((amountAjaxResult) => {
console.log('submit now', amountAjaxResult.form.amount);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="testForm">
<form>
<input type="number" class="amount" />
<button type="submit">Submit</button>
</form>
</div>
答案 2 :(得分:-1)
您可以使用:
function method1(){
// some code
}
function method2(){
// some code
}
$.ajax({
url:method1(),
success:function(){
method2();
}
})
函数完成后的嵌套函数:
function test () {
console.log('test');
}
function test2 (callback) {
console.log('test2');
callback();
}
test2(test);
可能是related