简体   繁体   English

如何在wordpress ajax请求处理程序中设置cookie?

[英]How do I set a cookie in a wordpress ajax request handler?

I am trying to set a cookie in a wp ajax request handler without any success. 我试图在wp ajax请求处理程序中设置一个cookie而没有任何成功。
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') }
});

Here is the plugin: 这是插件:

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');

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': 为了使其工作,您必须将cookie路径设置为网站的“/”(根),而不是当前的“post”或“dirname”:

Instead of: 代替:

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

Use: 使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 AJAX 请求设置 cookie 值? - How to set cookie value with AJAX request? 如何修复 WordPress 插件对表单处理程序文件的 ajax 请求。 (我自己正在开发一个插件) - How to fix ajax request to the form handler file from the WordPress plugin. (I am developing a plugin myself) 如何在页面加载之前使用 WordPress ajax 设置 cookie 和重定向 - How can I use WordPress ajax to set a cookie and redirect before a page loads 我如何在php中使用Ajax请求服务器端在Chrome中设置Cookie - How can i set the cookie in chrome using ajax request server side in php 在wordpress中的ajax请求上出现非法调用错误(如果未设置processData且无法找到操作处理程序) - Illegal invocation error (if processData not set and can not find action handler if set) on ajax request in wordpress 如何在iOS Phonegap中设置cookie? - How do I set a cookie in iOS Phonegap? Ajax请求后无法设置cookie - unable to set cookie after ajax request Extjs Ajax 请求中未正确设置 Cookie - Cookie not set correctly in Extjs Ajax request Cookie在Ajax请求之前设置,但响应使用较旧的Cookie IE - Cookie set before Ajax request but response use older cookie IE WordPress,我如何AJAX附加帖子 - WordPress, How Do I AJAX Additional Posts
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM