[英]Call php in HTML form on action but don't redirect
我有一个HTML表单如下:
<form id="ContactForm" name="ContactForm" method="post" action="emailinfo.php">
然后是一个调用verify()
的提交按钮:
<a href="#" class="button1" onClick="verify()">Send</a>
verify
定义如下:
function verify() {
if(document.getElementById("name").value=="" || document.getElementById("email").value=="") {
alert("Please enter a name and an email.");
} else {
alert("Looks good, sending email");
document.getElementById('ContactForm').submit();
}
}
目前,当我点击提交按钮时,浏览器会重定向到emailinfo.php
,这只是一个空白的白色屏幕,因为该php
文件只发送一封电子邮件emailinfo.php
执行任何其他操作。 如何在不重定向的情况下运行该php
文件?
您要做的是使用AJAX在单击按钮时向emailinfo.php文件发送请求。 将表单操作设置为空白将导致表单发布到您所在的同一页面。
如果你正在使用jQuery,通过ajax提交表单非常容易:
$(document).ready( function() {
$('.button1').click(function(){
var f = $('#ContactForm');
$.ajax({
type: "POST",
url: "emailinfo.php",
data: f.serialize()
});
});
});
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
function verify() {
if(document.getElementById("name").value=="" || document.getElementById("email").value=="") {
alert("Please enter a name and an email.");
} else {
alert("Looks good, sending email");
//document.getElementById('ContactForm').submit();
var name=$('#name').val();
var email=$('#email').val();
var formData = "name="+name+"&email="+email;
$.ajax({
url : "emailinfo.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
//data - response from server
alert(data);
},
});
}
}
</script>
<form id="ContactForm" name="ContactForm" method="post" action="">
<input type="text" name="name" id="name"/>
<input type="text" name="email" id="email"/>
<a href="#" class="button1" onClick="verify()">Send</a>
</form>
ContactFormFirst改变a
到一个按钮标签,然后分配verify()
它的onclick。 然后在verify()
。 使用ajax将表单中的值发布到emailinfo.php
。
你可以用
$.post(
"emailinfo.php",
$( "#ContactForm" ).serialize(),
function( data ) {
/* do things with responce */
} );
我在这种情况下通常做的是ajax,但是如果你不想使用ajax,你可以简单地添加'return false',因为它在使用表单提交时不会被重定向:
function verify()
{
if(document.getElementById("name").value=="" ||document.getElementById("email").value=="")
{
alert("Please enter a name and an email.");
}
else
{
alert("Looks good, sending email");
document.getElementById('ContactForm').submit();
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.