我可以使用preventDefault();在ajax回调中? [英] Can I preventDefault(); inside of an ajax callback?

查看:103
本文介绍了我可以使用preventDefault();在ajax回调中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些表格验证,而我正在努力完成我想要完成的任务。我希望能够在字段的模糊处验证我的邮政编码,但也可以调用相同的函数来验证表单提交时的zip,并防止在邮政编码无效时提交表单。我的代码(一般来说)是这样的。

I'm doing some form validation, and I'm having trouble with what I'm trying to accomplish. I want to be able to validate my zip code on blur of the field, but also call the same function to validate zip on submit of the form, and prevent the form from being submitted if the zip code is invalid. My code (generically) goes something like this.

function validateZipCode(event){
    $.getJson(
        url,
        params,
        function(data){
            if(data.response === false){
                someError.show();
                event.preventDefault(); //stop the form from being submitted
            }    
        }
    );
}

$('#someForm').submit(function(event){
    validateZipCode(event);
});

$('#zipInput').blur(function(event){
    validateZipCode(event);
})

我已尝试使用此 jQuery将更多参数传递给回调帖子,但我似乎无法完成我所需要的。任何帮助都表示赞赏。

I've tried using the methods located in this jQuery pass more parameters into callback post, but I still can't seem to accomplish what I need. Any help is appreciated.

推荐答案

不,当AJAX事件的回调触发时,该事件已经冒泡并且提交的表格。您可以实现此目的的一种方法是从提交中取消表单,然后在从AJAX请求传递要求时手动提交。

No, by the time the callback from the AJAX event fires, the event will have already bubbled and the form submitted. One way you could accomplish this is cancel the form from submitting and then submit it manually if it passes the requirements from the AJAX request.

这篇关于我可以使用preventDefault();在ajax回调中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆