简体   繁体   English

我的提交表单不是第一次发送,而是在单击提交按钮时第二次发送

[英]my submit form doesn't send in first time but send in second time when submit button click

I have a form that I check its values with ajax and if valid then send to another page here is my index.js 我有一个表单,我使用ajax检查其值,如果有效,则发送到另一页,这里是我的index.js

 $("#form").submit(function(event){
    var thisForm = $(this);
    $(".ajaxLogo").show();
    event.preventDefault();

    // do some stuff

    $.ajax({
        url: '/ajax/Check',
        data: data,
        dataType: 'json',
        success:function(result){
            // ....
            // check some situations that if form is not valid don't send the form
            // ....

            if(result.isOK=='1'){
                alert("I am before this line");
                thisForm.unbind('submit').submit(); // send request to '/'
                alert("I am after that line");
            }
        }
    });
});

My problem occurs when page loads. 页面加载时发生我的问题。 The first time I click the submit button I see two alert s in browser but nothing happens (form doesn't submit and page doesn't refresh)! 第一次单击“提交”按钮时,我在浏览器中看到两个alert ,但未发生任何反应(表单未提交,页面未刷新)! However the second time, the form sends and page refreshes. 但是,第二次,该窗体发送并刷新页面。 Why? 为什么?

Also, the second time I don't see the two alert s in the browser. 另外,第二次我在浏览器中看不到这两个alert

I will suggest that u keep a global var isok ='' and if all result.isok ="1" than donot do e.preventDefault();. 我建议您保持全局变量isok ='',如果所有result.isok =“ 1”都不要执行e.preventDefault();。 Its not neat way but might solve problem to keep submitting form until ajax validation is done without major code changes. 它不是一种整洁的方法,但是可以解决问题,使提交表单一直保持直到ajax验证完成而无需重大代码更改。

var isok ='';
$("#form").submit(function(event){
var thisForm = $(this);
$(".ajaxLogo").show();
if(isok != '1')
event.preventDefault();

// do some stuff

$.ajax({
    url: '/ajax/Check',
    data: data,
    dataType: 'json',
    success:function(result){
        // ....
        // check some situations that if form is not valid don't send the form
        // ....

        if(result.isOK=='1'){
             isok='1';
            alert("I am before this line");
            thisForm.unbind('submit').submit(); // send request to '/'
            alert("I am after that line");
        }
    }
});
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM