如何在wordpress ajax请求处理程序中设置cookie? [英] How do I set a cookie in a wordpress ajax request handler?

查看:75
本文介绍了如何在wordpress ajax请求处理程序中设置cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在wp ajax请求处理程序中设置cookie,但没有成功。
希望有人可以帮助我。


这是客户端代码:

I am trying to set a cookie in a wp ajax request handler without any success.
Hope someone can help me.

Here is client-side code:

var foo = $('#foo');
$.ajax({
    url: 'http://127.0.0.1/wordpress/wp-admin/admin-ajax.php',
    type:   'post',
    dataType:   'json',
    cache:  'false',
    data: { 'action' : 'foo', 'foo' : foo.val(), 'nonce' : foo.data('nonce') },
    success: function(data) { console.debug(data) },
    error: function() { console.error('fail') }
});

这里是插件:

function foo() {
    check_ajax_referer( 'foo-my-nonce', 'nonce', 'what?!' );

    if (isset($_POST['foo'])) {
        $dir = pathinfo($_SERVER['REQUEST_URI']);
        $dir['dirname'] = $dir['dirname'].'/';
        setcookie('foo', $_POST['foo'], time()+62208000, $dir['dirname'], $_SE    RVER['HTTP_HOST']);

        $output = array('response' => 'success', 'message' => 'have fun');
    }
    else
        $output = array('response' => 'failed', 'message' => 'you are a loser');

    header("Content-type: application/json");
    echo json_encode( $output );
    exit;
 }

 add_action('wp_ajax_nopriv_foo','foo');


推荐答案

好的,我解决了这个问题。
为了使其正常工作,必须将cookie路径设置为网站的 /(根目录),而不是当前的 post或 dirname:

Ok guys I fixed that. In order to make it working you must set the cookie path to "/" (the root) of the website, instead of the current 'post' or 'dirname':

而不是:

setcookie('foo',$ _POST ['foo'],time()+ 62208000,$ dir ['dirname'],$ _SERVER ['HTTP_HOST']);

使用:

setcookie('foo',$ _POST ['foo'],time()+ 62208000,'/',$ _SERVER ['HTTP_HOST']);

这篇关于如何在wordpress ajax请求处理程序中设置cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆