2015-07-21 130 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

謝謝,讓我分析一下我的代碼。 –