在 wordpress 和 jQuery 下,在 ajax 将调用回传回服务器期间,您如何保留用户登录信息?
我在我的wordpress网站上使用woocommerce。 我已经在jQuery下实现了ajax post操作,这些操作需要在PHP代码中输入当前用户的会话。 我不愿意提出自定义身份验证解决方案。
如您所知,运行 $.post 或 $.ajax 会使您的 php 代码在诸如 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 post 将在自定义 php 操作中维护当前用户的会话和登录信息。