javascript - 表单提交后无法重定向

标签 javascript php html forms redirect

我在包含表单数据的 HTML 页面上有一个表单,并且希望在用户按下提交按钮并通过电子邮件发送信息后将用户重定向到一个新的 URL 页面。使用以下按钮调用表单。

<div class="btnp"><input type="submit"  value="Continue to Billing" ></div>

表单然后通过邮寄将数据发送到我的 PHP 文件。我不需要成功回显消息,我只想将 URL 重定向到付款页面。下面是我设置的 PHP 文件。我正在尝试提交,发送带有表单日期的电子邮件,然后重定向到一个新的 html url。

<?php
//Retrieve form data. 
//POST
$URL = "http://www.google.com"; 
$fname  = $_POST['fname'];              
$zip = $_POST['zip'];       
$phone = $_POST['phone'];       
$email = $_POST['email'];       

    //recipient - change this to your name and email
    $to = 'sales@mysite.com';   
    //sender
    $from = $fname . ' <' . $email . '>';

    //subject and the html message
    $subject = 'New User: ' . $fname;   
    $message = '
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head></head>
    <body>
        <table>
            <tr><td>First Name</td><td>' . $fame . '</td></tr>      
            <tr><td>Zip</td><td>' . $zip . '</td></tr>      
            <tr><td>Telephone</td><td>' . $phone . '</td></tr>  
            <tr><td>Email</td><td>' . $email . '</td></tr>  
        </table>
    </body>
    </html>';

    //send the mail
    $result = sendmail($to, $subject, $message, $from);

    if ($_POST) 
        if ($result) header('Location: '.$URL);
        else echo 'Sorry, unexpected error. Please try again later';

    //Simple mail function with HTML header
    function sendmail($to, $subject, $message, $from) {
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
    $headers .= 'From: ' . $from . "\r\n";  
    $result = mail($to,$subject,$message,$headers);
    }       
?>    

最佳答案

使用“header”功能:

header("location: result.php");

你不能在屏幕上输出/打印/回显任何东西,所以试试这个:

if ($_POST) 
        if ($result) header("location: result-page.php");
        else echo 'Sorry, unexpected error. Please try again later';

或者您可以使用 javascript 打印成功消息并重定向:

if ($_POST) 
        if ($result) { 
            print "<script>alert('Ok, email sent');</script>";
            print "<script>window.open('result-page.php','_self');</script>";
        }else{
            print 'Sorry, unexpected error. Please try again later';
        }

关于javascript - 表单提交后无法重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19915067/

相关文章:

HTML CSS flexbox 图像和文本

javascript - jQuery - OnClick,在单击时始终更改表格单元格的背景颜色

javascript - 是否可以使用 google 闭包编译器更改 javascript?

php - MySQL 搜索多个表

javascript - 如果页面上存在字符串则执行函数

php - Codeigniter mysql 数据库与 Amazon RDS 的连接失败

php - 如何在不是很 "Testy"的环境中使用 TDD

html - 多个导航标签冲突

javascript - Bootstrap 轮播在第一张图片上向左滑动消失

javascript - 了解 JavaScript 类方法和原型(prototype)