javascript 如何避免在php表单提交中重新加载页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23196423/
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
How to avoid page reload in php form submission
提问by raju
I am currently using php in my html page and there is an action in the same page which gets executed upon form submission. Currently whole form gets reloaded while I want the php action to be run in the background with out reloading. How do I do it. I would also want to clear the text box after submit button is clicked. Following is the code I am currently using
我目前在我的 html 页面中使用 php,并且在同一页面中有一个在表单提交时执行的操作。当前整个表单被重新加载,而我希望 php 操作在后台运行而不重新加载。我该怎么做。我还想在单击提交按钮后清除文本框。以下是我目前使用的代码
<html>
<head>
</head>
<body>
<form action="index.php" method="post" role="form">
<input type="email" placeholder="Enter email" name="email_address">
<button class="btn btn-primary custom-button red-btn">Sign Up</button>
</form>
<?php
if(isset($_POST['email_address']) !(trim($_POST['email_address']) == ''))
// do some action
}
?>
</body>
</html>
Note: Following code worked for me
注意:以下代码对我有用
<script type="text/javascript">
$('#contactForm').submit(function () {
$.post("mailer.php",$("#contactForm").serialize(), function(data){
});
return false;
});
</script>
回答by Praveen Kumar Purushothaman
You need to use AJAX for this, for without reloading. Or, if you want to do it without disturbing the page, you need to set target.
您需要为此使用 AJAX,因为无需重新加载。或者,如果您想在不打扰页面的情况下进行操作,则需要设置target.
Using AJAX
使用 AJAX
$("form").submit(function(){
$.post($(this).attr("action"), $(this).serialize());
return false;
});
Using target
使用 target
<form action="index.php" method="post" role="form" target="_blank">
回答by Chetan Gawai
Using ajax
使用 ajax
HTML
HTML
<html>
<head>
</head>
<body>
<form id="myform"><!--changge-->
<input type="email" placeholder="Enter email" name="email_address">
<button class="btn btn-primary custom-button red-btn" id="signup">Sign Up</button>
</form>
</body>
</html>
<script>
$(document).ready(function()
{
$('#signup').click(function()
{
$.ajax({
url:'index.php',
method:'post',
data : $('#myform').serialize(),
success:function()
{
}
)};
);
});
</script>
回答by sandipshirsale
You can try this
你可以试试这个
<html>
<head>
</head>
<body>
<form id="myform" action="index.php"><!--changge-->
<input type="email" placeholder="Enter email" name="email_address">
<button class="btn btn-primary custom-button red-btn" id="signup">
Sign Up</button>
</form>
<script>
$(document).ready(function(){
$('#signup').click(function(){
$.post($(this).attr("action"), $("#myform").serialize(),function(response){
alert(response) // you can get the success response return by php after submission success
});
)};
});

