【问题标题】:redirect page upon form submit after AJAX request that calls PHP function在调用 PHP 函数的 AJAX 请求后提交表单时重定向页面
【发布时间】:2017-01-24 14:54:45
【问题描述】:

我有一个 HTML 页面 (index.html),它收集电子邮件地址并通过 AJAX POST 请求将其提交到服务器。单击提交按钮时,javascript 函数通过 AJAX 执行发布请求,然后页面提交给自身。我需要修改它,以便页面提交到另一个页面 (thankyou.html) 而不是自身。我不确定如何在 PHP 中执行此操作。提交表单并执行 AJAX 查询后,有没有办法重定向 PHP 页面?

我不确定是否应该用 Javascript 或 HTML 或 PHP 重定向页面。

这是index.html中的表格:

       <form class="email-form" method="POST" validate>
            <div class="email-input-container register-info-email">
                <input class="email-input" type="email" autocapitalize="off" autocorrect="off" autocomplete="off" required name="MERGE0" id="MERGE0" placeholder="Email Address" pattern="[a-z0-9._%+-]+@[a-z0-9-]+\.[a-z]{2,63}$" aria-label="Email Address">
                <input id="sub-button" type="submit" class="submit-button" value="Submit" >
                <span class="success-message"><span class="sr-only">We got you</span></span>
            </div>
        </form>

这是 PHP 中的 post 请求 (post.php)

if ( isset($_POST['email']) ) :

    $data = [
            'email' => $_POST['email']
    ];

    if ( isset($_POST['platform']) ) :

            $data["device"] = $_POST['platform'];

    endif;

    syncMailchimp($data);

endif;

这是 AJAX 请求:

        $.ajax({
            type: "POST",
            url: 'post.php',
            data: data,
            success: function(data, status) {

                var message = JSON.parse(data).message;

                if (message == "error") {

                    $('.email-form small').html('An error has occurred. Please try submitting again.');
                    smallHighlight();

                } else if (message == "subscribed") {

                    $('.email-form small').html('You are already subscribed');
                    smallHighlight();

                } else {

                    $('.email-form').addClass('form-success');
                    $('.email-form small').attr('style', '');

                }

            },

【问题讨论】:

  • 如果调用PHP后需要重定向,请使用header FROM php重定向

标签: javascript php html ajax


【解决方案1】:

如果你想重定向到另一个页面,请在表单提交成功后放置这个

window.location = "http://www.example.com/thankyou.html";

编辑:你不应该在 PHP 中处理这个重定向,因为这是异步调用。您需要在提交脚本中以某种方式引用它

希望对你有帮助

【讨论】:

  • 会不会进入AJAX调用的成功函数中?
  • 是的,它应该或多或少像这样:rest of the code …else { window.location = "http://www.example.com/thankyou.html"; }
【解决方案2】:

在 PHP 中你可以使用它。

header('Location: http://www.example.com/thankyou.html');

在 Javascript 中

window.location.replace("http://www.example.com/thankyou.html");

window.location.href = "http://www.example.com/thankyou.html";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 2020-05-27
    • 1970-01-01
    相关资源
    最近更新 更多