在字段中没有任何数据的情况下,按下发送按钮时,如何防止页面刷新?

验证设置工作正常,所有字段都变红,但随后页面立即刷新。我对JS的了解比较基础。

特别是,我认为底部的processForm()函数是“坏”的。

HTML

<form id="prospects_form" method="post">
    <input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" />
    <input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" />
    <input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" />
    <textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
        
    <button id="form_send" tabindex="5" class="btn" type="submit" onclick="return processForm()">Send</button>
    <div id="form_validation">
        <span class="form_captcha_code"></span>
        <input id="form_captcha" class="boxsize" type="text" name="form_captcha" placeholder="Enter code" tabindex="4" value="" />
    </div>
    <div class="clearfix"></div>
</form>

JS

$(document).ready(function() { 

// Add active class to inputs
$("#prospects_form .boxsize").focus(function() { $(this).addClass("hasText"); });
$("#form_validation .boxsize").focus(function() { $(this).parent().addClass("hasText"); });
// Remove active class from inputs (if empty)
$("#prospects_form .boxsize").blur(function() { if ( this.value === "") { $(this).removeClass("hasText"); } });
$("#form_validation .boxsize").blur(function() { if ( this.value === "") { $(this).parent().removeClass("hasText"); } });


 
///////////////////
// START VALIDATION
$("#prospects_form").ready(function() {
    
    // DEFINE GLOBAL VARIABLES
    var valName = $('#form_name'),
        valEmail = $("#form_email"),
        valEmailFormat = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
        valMsg = $('#form_message'),
        valCaptcha = $('#form_captcha'),
        valCaptchaCode = $('.form_captcha_code');
        


    // Generate captcha
    function randomgen() {
        var rannumber = "";
        // Iterate through 1 to 9, 4 times
        for(ranNum=1; ranNum<=4; ranNum++){ rannumber+=Math.floor(Math.random()*10).toString(); }
        // Apply captcha to element
        valCaptchaCode.html(rannumber);
    }
    randomgen();
    
    
    // CAPTCHA VALIDATION
    valCaptcha.blur(function() {
        function formCaptcha() {
            if ( valCaptcha.val() == valCaptchaCode.html() ) {
                // Incorrect
                valCaptcha.parent().addClass("invalid");
                return false;
            } else {
                // Correct
                valCaptcha.parent().removeClass("invalid");
                return true;
            }
        }
        formCaptcha();
    });
    
    // Remove invalid class from captcha if typing
    valCaptcha.keypress(function() {
        valCaptcha.parent().removeClass("invalid");
    });
    
    
    // EMAIL VALIDATION (BLUR)
    valEmail.blur(function() {
        function formEmail() {
            if (!valEmailFormat.test(valEmail.val()) && valEmail.val() !== "" ) {
                // Incorrect
                valEmail.addClass("invalid");
            } else {
                // Correct
                valEmail.removeClass("invalid");
            }
        }
        formEmail();
    });
    
    // Remove invalid class from email if typing
    valEmail.keypress(function() {
        valEmail.removeClass("invalid");
    });
    
    
    // VALIDATION ON SUBMIT
    $('#prospects_form').submit(function() {
        console.log('user hit send button');

        // EMAIL VALIDATION (SUBMIT)
        function formEmailSubmit() {
            if (!valEmailFormat.test(valEmail.val())) {
                // Incorrect
                valEmail.addClass("invalid");
            } else {
                // Correct
                valEmail.removeClass("invalid");
            }
        }
        formEmailSubmit();

        // Validate captcha
        function formCaptchaSubmit() {
            if( valCaptcha.val() === valCaptchaCode.html() ) {
                // Captcha is correct
            } else {
                // Captcha is incorrect
                valCaptcha.parent().addClass("invalid");
                randomgen();
            }
        }
        formCaptchaSubmit();
        
        
        // If NAME field is empty
        function formNameSubmit() {
            if ( valName.val() === "" ) {
                // Name is empty
                valName.addClass("invalid");
            } else {
                valName.removeClass("invalid");
            }
        }
        formNameSubmit();
        
        
        // If MESSAGE field is empty
        function formMessageSubmit() {
            if ( valMsg.val() === "" ) {
                // Name is empty
                valMsg.addClass("invalid");
            } else {
                valMsg.removeClass("invalid");
            }
        }
        formMessageSubmit();
    
    
        // Submit form (if all good)
        function processForm() {
            if ( formEmailSubmit() && formCaptchaSubmit() && formNameSubmit() && formMessageSubmit() ) {
                $("#prospects_form").attr("action", "/clients/oubc/row-for-oubc-send.php");
                $("#form_send").attr("type", "submit");
                return true;
            } else if( !formEmailSubmit() ) {
                valEmail.addClass("invalid");
                return false;
            } else if ( !formCaptchaSubmit() ) {
                valCaptcha.parent().addClass("invalid");
                return false;
            } else if ( !formNameSubmit() ) {
                valName.addClass("invalid");
                    return false;
                } else if ( !formMessageSubmit() ) {
                    valMsg.addClass("invalid");
                    return false;
                } else {
                    return false;
                }
            }
        });
    });
    // END VALIDATION
    /////////////////
});

当前回答

function ajax_form(selector, obj)
{

    var form = document.querySelectorAll(selector);

    if(obj)
    {

        var before = obj.before ? obj.before : function(){return true;};

        var $success = obj.success ? obj.success: function(){return true;};

        for (var i = 0; i < form.length; i++)
        {

            var url = form[i].hasAttribute('action') ? form[i].getAttribute('action') : window.location;

            var $form = form[i];

            form[i].submit = function()
            {

                var xhttp = new XMLHttpRequest();

                xhttp.open("POST", url, true);

                var FD = new FormData($form);

                /** prevent submiting twice */
                if($form.disable === true)

                    return this;

                $form.disable = true;

                if(before() === false)

                    return;

                xhttp.addEventListener('load', function()
                {

                    $form.disable = false;

                    return $success(JSON.parse(this.response));

                });

                xhttp.send(FD);

            }
        }
    }

    return form;
}

没有检查它是如何工作的。你也可以绑定(this),这样它就会像jquery ajaxForm一样工作

像这样使用它:

ajax_form('form',
{
    before: function()
    {
        alert('submiting form');
        // if return false form shouldn't be submitted
    },
    success:function(data)
    {
        console.log(data)
    }
}
)[0].submit();

它返回节点,所以你可以像上面的例子那样提交

到目前为止,它还不是完美的,但它应该工作,你应该添加错误处理或删除禁用条件

其他回答

如果你想使用纯Javascript,那么下面的代码段将是最好的。

假设:

HTML:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Form Without Submiting With Pure JS</title>
        <script type="text/javascript">
            window.onload = function(){
                /**
                 * Just Make sure to return false so that your request will not go the server script
                 */
                document.getElementById('simple_form').onsubmit = function(){
                    // After doing your logic that you want to do 

                    return false 
                }
            }
        </script>
    </head>
    <body>

    </body>
</html>
<form id="simple_form" method="post">
    <!-- Your Inputs will go here  -->
    <input type="submit" value="Submit Me!!" />
</form>

希望它对你有用!!

<form onsubmit="myFunction(event)">
    Name : <input type="text"/>
    <input class="submit" type="submit">
  </form>
  <script>
  function myFunction(event){
    event.preventDefault();
    //code here
  }
  </script>

如果不使用action,只需在action属性中使用"javascript:"即可。

用JS做到这一点的最好方法是使用preventDefault()函数。 考虑下面的代码作为参考:

function loadForm(){
    var loginForm = document.querySelector('form'); //Selecting the form
    loginForm.addEventListener('submit', login);    //looking for submit
}

function login(e){
    e.preventDefault(); //to stop form action i.e. submit
}

当你给用户两种提交表单的可能性时,这个问题变得更加复杂:

通过单击一个AD hoc按钮 按回车键

在这种情况下,您将需要一个函数来检测按下的键,如果按下Enter键,您将提交表单。

现在IE的问题来了(在任何情况下版本11) 备注: Chrome和FireFox都不存在这个问题!

当你点击提交按钮时,表单被提交一次;很好。 当你点击回车键时,表单被提交了两次…您的servlet将被执行两次。如果服务器端没有PRG (post redirect get)体系结构,结果可能会出乎意料。

尽管解决方案看起来微不足道,但我花了很多时间来解决这个问题,所以我希望它可能对其他人有用。 该解决方案已成功测试,除其他外,在IE (v 11.0.9600.18426), FF (v 40.03)和Chrome (v 53.02785.143 m 64位)

源代码HTML和js在代码片段中。这里描述了原理。 警告:

您不能在代码片段中测试它,因为post操作不是 定义并按Enter键可能会干扰stackoverflow。

如果你遇到了这个问题,那么只需复制/粘贴js代码到你的环境中,并使其适应你的上下文。

/* * inForm points to the form */ var inForm = document.getElementById('idGetUserFrm'); /* * IE submits the form twice * To avoid this the boolean isSumbitted is: * 1) initialized to false when the form is displayed 4 the first time * Remark: it is not the same event as "body load" */ var isSumbitted = false; function checkEnter(e) { if (e && e.keyCode == 13) { inForm.submit(); /* * 2) set to true after the form submission was invoked */ isSumbitted = true; } } function onSubmit () { if (isSumbitted) { /* * 3) reset to false after the form submission executed */ isSumbitted = false; return false; } } <!DOCTYPE html> <html> <body> <form id="idGetUserFrm" method="post" action="servletOrSomePhp" onsubmit="return onSubmit()"> First name:<br> <input type="text" name="firstname" value="Mickey"> <input type="submit" value="Submit"> </form> </body> </html>