jQuery 提交表单后防止重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4038567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:33:09  来源:igfitidea点击:

Prevent redirect after form is submitted

jqueryhtmlformsredirect

提问by Robert Pessagno

I have an HTML form that submits an email with PHP, and when it submits, it redirects to that PHP page. Is there a way to prevent this redirect from happening? I built an animation with jQuery that I want to occur instead of redirecting. I tried return false;, but it wouldn't work. Here's my function:

我有一个 HTML 表单,它使用 PHP 提交电子邮件,当它提交时,它会重定向到该 PHP 页面。有没有办法防止这种重定向发生?我用 jQuery 构建了一个动画,我希望它发生而不是重定向。我试过 return false;,但它不起作用。这是我的功能:

$(function() {
    $('.submit').click(function() {
        $('#registerform').submit();
        return false;
    }); 
});

Here's the opening form tag:

这是打开表单标签:

<form id="registerform" action="submit.php" method="post">

And the submit button:

和提交按钮:

<input type="submit" value="SUBMIT" class="submit" />

回答by Bruce Armstrong

You should post it with ajax, this will stop it from changing the page, and you will still get the information back.

您应该使用 ajax 发布它,这将阻止它更改页面,并且您仍然会得到信息。

$(function() {
    $('form').submit(function() {
        $.ajax({
            type: 'POST',
            url: 'submit.php',
            data: { username: $(this).name.value, 
                    password: $(this).password.value }
        });
        return false;
    }); 
})

See Post documentation for JQuery

请参阅JQuery 的 Post 文档

回答by bozdoz

Instead of return false, you could try event.preventDefault(); like this:

您可以尝试 event.preventDefault(); 而不是 return false。像这样:

$(function() {
$('#registerform').submit(function(event) {
    event.preventDefault();
    $(this).submit();
    }); 
});

回答by Derek Adair

Using Ajax

使用 Ajax

Using the jQuery Ajaxrequest method you can post the email data to a script (submit.php). Using the successcallback option to animate elements after the script is executed.

使用jQuery Ajax请求方法,您可以将电子邮件数据发布到脚本 (submit.php)。success在脚本执行后使用回调选项为元素设置动画。

note- I would suggest utilizing the ajax Response Object to make sure the script executed successfully.

注意- 我建议使用 ajax 响应对象来确保脚本成功执行。

$(function() {
    $('.submit').click(function() {
        $.ajax({
            type: 'POST',
            url: 'submit.php',
            data: 'password=p4ssw0rt',
            error: function()
            {
               alert("Request Failed");
            },
            success: function(response)
            {  
               //EXECUTE ANIMATION HERE
            } // this was missing
        });
        return false;
    }); 
})

回答by mwotton

If you want the information in the form to be processed by the PHP page, then you HAVE to make a call to that PHP page. To avoid a redirection or refresh in this process, submit the form info via AJAX. Perhaps use jQuery dialog to display the results, or your custom animation.

如果您希望 PHP 页面处理表单中的信息,则必须调用该 PHP 页面。为避免在此过程中重定向或刷新,请通过 AJAX 提交表单信息。也许使用 jQuery 对话框来显示结果,或者您的自定义动画。

回答by Matricore

$('#registerform').submit(function(e) {
   e.preventDefault();
   $.ajax({
        type: 'POST',
        url: 'submit.php',
        data: $(this).serialize(),
        beforeSend: //do something
        complete: //do something
        success: //do something for example if the request response is success play your animation...
   });

})

回答by Amir Raminfar

If you can run javascript, which seems like you can, create a new iframe, and post to that iframe instead. You can do <form target="iframe-id" ...>That way all the redirects happen in the iframe and you still have control of the page.

如果您可以运行 javascript,这似乎可以,请创建一个新的 iframe,然后发布到该 iframe。您可以这样做<form target="iframe-id" ...>,所有重定向都发生在 iframe 中,并且您仍然可以控制页面。

The other solution is to also do a post via ajax. But that's a little more tricky if the page needs to error check or something.

另一种解决方案是也通过ajax发帖。但是如果页面需要错误检查或其他东西,那就有点棘手了。

Here is an example:

下面是一个例子:

$("<iframe id='test' />").appendTo(document.body);
$("form").attr("target", "test");

回答by Steven Zurek

With out knowing exactly what your trying to accomplish here its hard to say but if your spending the time to solve this problem with javascript an AJAX request is going to be your best bet. However if you'd like to do it completely in PHP put this at the end of your script, and you should be set.

不知道你想在这里完成什么很难说,但如果你花时间用 javascript 解决这个问题,AJAX 请求将是你最好的选择。但是,如果您想完全在 PHP 中完成,请将其放在脚本的末尾,并且您应该进行设置。

if(isset($_SERVER['HTTP_REFERER'])){
    header("Location: " . $_SERVER['HTTP_REFERER']);    
} else {
    echo "An Error";
}

This will still cause the page to change, twice, but the user will end on the page initiating the request. This is not even close to the right way to do this, and I highly recommend using an AJAX request, but it will get the job done.

这仍然会导致页面更改两次,但用户将在发起请求的页面上结束。这甚至不是正确的方法,我强烈建议使用 AJAX 请求,但它可以完成工作。

回答by gargAman

You can use as below

您可以使用如下

e.preventDefault() 

If this method is called, the default action of the event will not be triggered.

如果调用此方法,则不会触发事件的默认动作。

Also if I may suggest read this: .prop() vs .attr()

另外,如果我建议阅读此内容: .prop() vs .attr()

I hope it will help you,

我希望它会帮助你

code example:

代码示例:

$('a').click(function(event){
    event.preventDefault();
    //do what you want
  } 

回答by flix

Just like Bruce Armstrong suggested in his answer. However I'd use FormData:

就像布鲁斯·阿姆斯特朗在他的回答中所建议的那样。但是我会使用FormData

$(function() {
    $('form').submit(function() {
        var formData = new FormData($(this)[0]);
        $.ajax({
            type: 'POST',
            url: 'submit.php',
            data: formData,
            processData: false,
            contentType: false,
        });
        return false;
    }); 
})

回答by Parris Varney

The simple answer is to shoot your call off to an external scrip via AJAX request. Then handle the response how you like.

简单的答案是通过 AJAX 请求将您的呼叫发送到外部脚本。然后处理您喜欢的响应。