簡體   English   中英

使用ajax發布的Wordpress,而不會失去woocommerce的用戶登錄會話

[英]Wordpress using ajax post without losing the user's login session for woocommerce

如何在ajax發布回調到wordpress和jQuery下的服務器時保持用戶登錄信息?

我在wordpress網站上使用woocommerce。 我在jQuery下實現了ajax post操作,需要當前用戶在PHP代碼中的會話。 我不願意提出自定義身份驗證解決方案。

如您所知,運行$ .post或$ .ajax將使您的php代碼在if ( !is_user_logged_in() )...類的事情上失敗if ( !is_user_logged_in() )...

這是一個簡單的代碼塊,它讀取$_COOKIE作為當前用戶的會話信息,並創建一個現成的回調, jQuery稍后將使用該回調來維護會話上下文:

//insert somewhere inside functions.php

add_action('wp_head', 'pluginname_ajaxurl');
function pluginname_ajaxurl() {
?>
<script type="text/javascript">
  function ajaxSetup()
  {
      //Return a cookie setup function inserted into the ajax call
    return function(xhr, settings) {
      <?php
      foreach ( $_COOKIE as $key => $value )
        echo "xhr.setRequestHeader('$key', '$value');\n"
      ?>
      return true;
    };
  }
  var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php

現在,您的ajax調用將如下所示:

$.ajax({
type: "POST",
url: '/', //ajaxurl, depending on your ajax hook implementation
beforeSend: ajaxSetup(),  //Pass in the cookie information into header
data: {action: 'my_action', some_data: 'info_about_things'},
dataType: "json",
success: function (data) {
  if (data.success)
    alert("Awesome");
  else
    alert("Maybe next time");
}
});

現在,ajax發布將在自定義php操作中維護當前用戶的會話和登錄信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM