我试图让“添加到购物车”按钮仅在 ajax 调用成功返回时执行实际提交(继续到添加到购物车页面),否则显示 ajax 结果中给出的消息,并且并不实际执行提交。
这就是我目前所拥有的
$("#addtocart").submit(function(event){
var data = $(this).serialize();
$.ajax({
type: "POST",
url: "/cart/check",
dataType:"json",
data: data
}).done(function(data){
$("#message").html(data.message);
if (data.success == true) this.submit();
})
event.preventDefault();
});
如果我删除 event.preventDefault() ,无论检查如何,表单总是会提交,如果我保留它,它永远不会提交。也许 this.submit() 不是正确的解决方案。我在某处读到,只有在验证失败时才应调用 Preventdefault,但如果我尝试
if (data.success == false) event.preventDefault();
无论 data.success 为 true 或 false,它仍然提交表单
如果有人能找到正确的解决方案,我将非常感激
最佳答案
完成回调中的
this
是 jqXhr 对象而不是表单,如果要将表单绑定(bind)为完成函数的上下文,请使用“上下文配置”。
$.ajax({
context: this, //<-- the form
...
关于javascript - ajax验证成功后才提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36971824/