在.submit()表单后重定向

时间:2012-05-28 20:38:10

标签: jquery forms redirect submit

我有一个HTML表单,它使用div(submitme)来触发以下代码......然后代码使用bValidator插件来验证表单字段,然后在提交表单之前检查一个honeypot字段是否为空....

当我排除“window.location ...”等时,.submit()会工作并发布表单,但是当包含它时;验证/蜜罐仍然有效但没有表格提交。

我是JQUERY的新手,想知道是否有一些简单的遗漏或更好的方式来写下面的内容:

$("#submitme").click(function(){
    if($('#right-body-div').data('bValidator').validate()) {

        if ($("#honeypot").val() == "") {
                $('#pgpost').submit();
                window.location = "http://www.homepage.co.uk/thankyou";    
                return true;
              }
           window.location = "http://www.homepage.co.uk/nothankyou";
           return false;
    }
});

如果可能,id就是在不使用AJAX / PHP的情况下完成此任务。

非常感谢您的想法。

1 个答案:

答案 0 :(得分:4)

$('#pgpost').submit(function(e) {  // this handles the submit event
    if($('#right-body-div').data('bValidator').validate()) {
        if ($("#honeypot").val() == "") {
            /*
             * url = $('#pgpost').val('action');
             * data = $('#pgpost').serialize();
             * $.post(url, data, function() {
             *     window.location = "http://www.homepage.co.uk/thankyou";
             * });
             */
            window.location = "http://www.homepage.co.uk/thankyou";
        }
        else {
            window.location = "http://www.homepage.co.uk/nothankyou";
        }
    }

    e.preventDefault();
    return false;
    /*
     * the 2 lines above are meant to prevent the normal behaviour
     * that the <form> would have (which is to submit via browser).
     * 
     * e.preventDefault() is the jquery way prevent the normal behaviour
     * return false is the legacy way to do it, you can use either or both
     * 
     * the reason for which the code didn't validate your form is
     * that e.prevenDefault() was only called inside the IF statement
     * which means that it would only be called if the field was
     * already in valid form. So basically if the form was invalid the normal
     * behaviour is not prevented and the browser submits the form, if the form
     * was valid the submit behaviour was prevented and the redirect was used.
     * 
     */
});

$("#submitme").click(function(){
    $('#pgpost').submit(); // this triggers the submit event
}); 

通过JavaScript处理提交事件时,您可以:

  • 始终阻止正常行为(我们的情况):
    • 当表单通过JavaScript有效时submit the data,您可能会在提交之前对其进行处理;
    • 当表单无效时,您会显示错误消息;
  • 仅在表单无效时阻止正常行为
    • 当表单有效时,您允许正常行为(浏览器提交数据);
    • 当表单无效时,您会显示错误消息;

您的案例中的错误消息应说明蜜罐不应为空。

在以下情况下防止正常行为是有意义的:   - 您需要在将数据发送到服务器之前处理数据(创建新值,更改当前值; 不验证);   - 您需要避免页面刷新,以便通过AJAX发送;

仅仅为了验证,防止该行为没有意义,因为您可以验证然后允许正常行为继续。