在操作上以 HTML 形式调用 php,但不重定向

Call php in HTML form on action but don't redirect

本文关键字:php 重定向 调用 操作上 HTML      更新时间:2023-09-26

>我有一个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文件只是发送电子邮件而不做任何其他事情。如何在不重定向到该文件的情况下运行该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>

ContactForm首先将该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;
  }
}