2015-07-21 42 views
1

我想让脚本通过使用PHP头函数来单击提交按钮来进行重定向。但是,它似乎并不奏效。任何想法如何让它与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; 

我试图取代$resultheader("Location: http://www.example.com/");,但没有奏效。

+0

您是否通过AJAX调用此PHP脚本?如果是这样,你应该返回类似'array('success'=> true,'location'=>'http:// ...')'并且在你的ajax回调中做重定向。 – Bjorn

+0

@Bjorn,是否应该替换$ result = json_encode(array('success'=> $ success_message)); $ result = json_encode(array('success'=> true,'location'=>'http://www.example.com')); ? –

+0

@Bjorn它返回true,但没有进行重定向。通过AJAX。 –

回答

0

您不能只是将代码更改为$result = header('Location: ...')的原因其实很简单。有了这个javascript调用为例:

$.post('/myscript.php', { et_lastname: 'Doe', email: '[email protected]' }, function(data) { 
    // do something 
}); 

会发生什么:

  1. 一个HTTP-POST呼叫通过AJAX作出/myscript.php
  2. 执行你的代码,订阅给定的电子邮件地址。
  3. PHP代码返回301
  4. AJAX调用将遵循重定向,但您的浏览器将保持在同一页面上。

你真正想要的是,当AJAX调用成功时,浏览器重定向到另一个页面。为了达到这个目的,你需要更新你的PHP和Javascript。

在你的PHP,你必须返回你想要的浏览器重定向到的位置,例如:

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

眼下,PHP脚本会返回一个JSON响应与位置键。除非我们告诉它,否则浏览器和javascript都不会执行任何操作:

$.post('/myscript.php', { et_lastname: 'Doe', email: '[email protected]' }, 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 
}); 
+0

谢谢,让我分析一下我的代码。 –