PHP头重定向表单提交不工作


PHP Header Redirect on Form Submission Not Working

我想让脚本做一个重定向的点击提交按钮使用PHP头函数。然而,它似乎不起作用。任何想法我怎么能得到它的工作与PHP头函数?

这是我认为相关的部分函数:-

switch ( $service ) {
    case 'mailchimp' :
        $lastname = sanitize_text_field( $_POST['et_lastname'] );
        $email = array( 'email' => $email );
        if ( ! class_exists( 'MailChimp' ) )
            require_once( get_template_directory() . '/includes/subscription/mailchimp/mailchimp.php' );
        $mailchimp_api_key = et_get_option( 'divi_mailchimp_api_key' );
        if ( '' === $mailchimp_api_key ) die( json_encode( array( 'error' => __( 'Configuration error: api key is not defined', 'Divi' ) ) ) );

            $mailchimp = new MailChimp( $mailchimp_api_key );
            $merge_vars = array(
                'FNAME' => $firstname,
                'LNAME' => $lastname,
            );
            $retval =  $mailchimp->call('lists/subscribe', array(
                'id'         => $list_id,
                'email'      => $email,
                'merge_vars' => $merge_vars,
            ));
            if ( isset($retval['error']) ) {
                if ( '214' == $retval['code'] ){
                    $error_message = str_replace( 'Click here to update your profile.', '', $retval['error'] );
                    $result = json_encode( array( 'success' => $error_message ) );
                } else {
                    $result = json_encode( array( 'success' => $retval['error'] ) );
                }
            } else {
                $result = json_encode( array( 'success' => $success_message ) );
            }
        die( $result );
        break;

我试图用header("Location: http://www.example.com/");代替$result,但它不起作用。

不能将代码更改为$result = header('Location: ...')的原因实际上很简单。以下面的javascript调用为例:

$.post('/myscript.php', { et_lastname: 'Doe', email: 'j.doe@example.com' }, function(data) {
    // do something
});

会发生什么:

  1. 通过AJAX对/myscript.php进行HTTP-POST调用
  2. 你的代码被执行,订阅给定的电子邮件地址。
  3. PHP代码返回301
  4. AJAX调用将跟随重定向,但您的浏览器将停留在同一页面上。

您真正想要的是,当AJAX调用成功时,浏览器将重定向到另一个页面。要实现这一点,您需要同时更新PHP和Javascript。

在您的PHP中,您必须返回您希望浏览器重定向到的位置,例如:

<?php
    $result = json_encode(array('location' => 'https://example.com/path/to/page'));

现在,PHP脚本只返回一个带有location键的json-response。浏览器和javascript不会对这些信息做任何事情,除非我们告诉它这样做:

$.post('/myscript.php', { et_lastname: 'Doe', email: 'j.doe@example.com' }, null, 'json').done(function(data) {
    // do something ...
    // redirect browser to page we provided in the ajax response
    window.location = data.location;
}).fail(function(data) {
    // handle the error
});