【问题标题】:jQuery ajax post doesn't redirect to php pagejQuery ajax 帖子不会重定向到 php 页面
【发布时间】:2017-05-27 17:59:52
【问题描述】:

我的网站上有一个带有 jQ​​uery ajax 调用的联系表单,但是当我单击按钮时没有看到 .php 页面。

这里是 ajax 调用:

    var data = {
        name: $("input.userName").val(),
        email: $("input.userEmail").val(),
        tel: $('input.userPhone').val(),
        message: "Projet de "+$("input.userName").val() + ", Tel : " + $('input.userPhone').val(),
            body: body
        };

    $.ajax({
        type: "POST",
        url: "acerola.php",
        data: data,
        success: function(data){
            console.log('ajax sucessfully sent');
        }
    });

使用 acerola.php:

<html>
<head><title>PHP Mail Sender</title></head>
<body>
<h1>OUIIiiii</h1>
<?php

echo "<h1>Coucou</h1>";

/* All form fields are automatically passed to the PHP script through the array $HTTP_POST_VARS. */
$name = $HTTP_POST_VARS['name'];
$email = $HTTP_POST_VARS['email'];
$tel = $HTTP_POST_VARS['tel'];
$message = $HTTP_POST_VARS['message'];
$body = $HTTP_POST_VARS['body'];

/* PHP form validation: the script checks that the Email field contains a valid email address and the Subject field isn't empty. preg_match performs a regular expression match. It's a very powerful PHP function to validate form fields and other strings - see PHP manual for details. */
if (!preg_match("/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/", $email)) {
  echo "<h4>Invalid email address</h4>";
  echo "<a href='javascript:history.back(1);'>Back</a>";
} elseif ($subject == "") {
  echo "<h4>No subject</h4>";
  echo "<a href='javascript:history.back(1);'>Back</a>";
} elseif ( /* Sends the mail and outputs the "Thank you" string if the mail is successfully sent, or the error string otherwise. */
    mail("plu@gmail.com", "Demande de devis web", $message . $body, "From:" . $email)
) {
  echo "<h4>Thank you for sending email</h4>";
  echo "<div>Thank you for sending email</div>";
} else {
  echo "<h4>Can't send email to $email</h4>";
}

?>
</body>
</html>

我希望将用户重定向到acerola.php。但用户停留在原始页面上。

【问题讨论】:

  • ajax data 怎么样?
  • 如果你想重定向不需要ajax,只需将你的数据提交到acerola.php
  • @ZakariaAcharki 请问如何正确执行此操作?
  • @Alexandru-IonutMihai 我在我的问题中添加数据
  • 你需要使用这个:data: JSON.stringify(data),,因为你需要将数据作为字符串发送到服务器。在acerola.php你必须使用JSON.parse()解析json,然后问题就解决了.

标签: php jquery ajax


【解决方案1】:

在 ajax 响应之后,使用 javascript 触发重定向。

$.ajax({
    type: "POST",
    url: "acerola.php",
    data: data,
    success: function(data){
        console.log('ajax sucessfully sent');
        window.location.replace('URL HERE')
    }
});

【讨论】:

  • 但是您可以在我的 php 脚本中看到 html 代码,我希望首先显示此代码,但它不会转到此页面 .php
  • 如果我这样做,变量不会在 php 页面中回显...例如echo $name什么都不显示....为什么??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-19
  • 2018-11-17
  • 2017-10-26
  • 1970-01-01
  • 2016-08-07
相关资源
最近更新 更多