从ajax成功函数内部提交表单,以检查值 [英] Submit a form from inside an ajax success function that checks the values

查看:88
本文介绍了从ajax成功函数内部提交表单,以检查值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过大约20篇或更多关于该主题的帖子,但它们对我来说没有意义或略有不同.

I've seen about 20 or more posts on the subject, but they either don't make sense to me or slightly different.

这也是一个非常简单的场景.我有一个表单,当它提交时,我进行了ajax调用,以查看该电子邮件是否已被其他用户接收.如果不接受,我想提交表单,如果不是,请不要提交表单.

It's a pretty simple scenario as well. I have a form, when it submits, I do an ajax call to see if the email is not taken already by another user. If not taken I want to submit the form, if it is, don't submit form.

这是HTML

<form id='greatForm' action='godothat.php' method='post'>
<input type='submit' id='email'>
<button>Send</button>
</form>

JS

$('#greatForm').submit(function(){


        // GET THE VARS
        var email = $('#email').val();


         $.ajax({ 
            data: { 'field1' : email  },
            type: 'GET', 
            dataType: 'json',
            url: 'url.php',
            beforeSend : function(){   },
            success: function(answer){   
                if(answer.error === false){
                         // Submit this form without doing the ajax call again
                } 
                if(answer.error === true){
                    // Not ok, don't submit this form
                }
            }
        });                               

        return false;   
    });

感谢您的帮助.

**更新** 也许我说的不对.我的意思是,如果"answer.error === false"为true,则submit函数应返回true.

** UPDATE ** Maybe I didn't phrase it right. What I mean is if the "answer.error === false" is true then the submit function should return true.

因此在AJAX上完成后,如果answer.error为false,则提交应为true,反之亦然...

So on AJAX complete, if answer.error is false, the submit should be true and vice versa...

这更有意义吗?

推荐答案

$('#greatForm').submit(function(){
    if(!$(this).attr('validated'))
    {
     // GET THE VARS
     var email = $('#email').val();


      $.ajax({ 
        data: { 'field1' : email  },
        type: 'GET', 
        dataType: 'json',
        url: 'url.php',
        beforeSend : function(){   },
        success: function(answer){   
            if(answer.error === false){
                   $('#greatForm').attr('validated',true);
                   $('#greatForm').submit();
            } 
            if(answer.error === true){
                //display the errors
            }
        }
     });
     return false;  
    }                            
   return true;
});

这应该可以解决问题,只要将已验证的属性添加到表单(如果已验证)即可. 并且只有在未预先设置属性的情况下,您才可以验证表单.

This should do the trick, you just add a property validated to the form if it's already validated. And you validate the form only if the attribute is not preset otherwise you submit.

这篇关于从ajax成功函数内部提交表单,以检查值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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