javascript - 如何使用php重定向按钮点击

标签 javascript php html

我在表单上使用了一个按钮。成功提交用户信息后,我试图通过单击按钮重定向到另一个页面。除重定向外,一切正常。这是我试过的代码。

HTML代码:

<form role="form" id="contact-form" method="get">
  <div class="form-group row">
      <input type="email" id="email" name="email" placeholder="Enter your email" required="required" class="form-control input-lg" />
      <input type="text" id="address" name="address" placeholder="Enter your address" required="required" class="form-control input-lg" />
      <button type="submit" class="btn btn-t-primary">Show Me Now!</button>
  </div>
</form>

Javascript 代码:

function contact() {
  $("#contact-us-form").submit(function (e) {
  e.preventDefault();
  e.stopImmediatePropagation();
  form = $(this);
  data = $(this).serialize();
  $.post("contact.php", data, function(response){
      form.trigger('reset');
  });
}

PHP代码:

<?php 
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
if (isset($_POST['email'])) {
    $email = $_POST['email'];
    $address= $_POST['address'];
    $subject = "Message from: ".$email;
    $content = "Email: " . $email."\n"
            . "Address: " . $address;
    $headers ='Reply-To: ' . $email . "\r\n";
    mail('example@gmail.com', $subject ,$content, $headers );
    header("Location:https://www.example.com");
    echo 1;
}else {
    echo 0;
}

?>

最佳答案

您不能从 PHP 重定向 ajax 请求,而是使用这个:

$(function() {

    $("#contact-form").submit(function(e) {
        e.preventDefault();
        e.stopImmediatePropagation();
        form = $(this);
        data = $(this).serialize();
        $.post("contact.php", data, function(response) {
            form.trigger('reset');
            //Redirection
            window.location.href = "https://www.google.com";
        });
    });

});

只需从您的 PHP 中删除此 header("Location:https://www.example.com");

希望对您有所帮助。

关于javascript - 如何使用php重定向按钮点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38689239/

相关文章:

javascript - React 应用程序中登录页面的路由保护

javascript - 如何为 droppable td 编写接受条件,以便它只接受表中的邻居 td

php - 合作伙伴网站托管的 Web 应用程序不公开源代码 - 可能吗?

php - MySQL 在插入之前进行检查

php - 联系表格 7 - Wordpress

html - 根据下面的宽度 <td> 确定 <td> 的宽度?

javascript - FullCalendar 错误 - Microsoft JScript 运行时错误 : Object doesn't support this property or method

javascript - AngularJS $compile 不会删除双 curl 表达式

html - 希望文本叠加对其背景做出响应

html - 使图像从 div 中弹出