dsgni26260 2016-06-27 18:40
浏览 98
已采纳

用AJAX的Wordpress setcookie

Firstly, I haven't seen any answers to similar questions that have sorted this. If you find one that already exists, please let me know.

Simple AJAX request that sets a cookie to store a timer expiry, the damn cookie isn't being set and I cannot work out why.

I'm using Vue Resource, so no jQuery please. In fact, I'm absolutely certain it has nothing to do with JS or the AJAX at all. It is posting fine and the "expiry" is being returned perfectly well.

The JS:

var sessionKey = document.querySelector('meta[name=dbs]').getAttribute('content');
if(sessionKey.length < 1){
    var data = {action: 'dbs_reservation'};
    this.$http.get(ajaxurl,data).then((response) => {
        this.sessionExpiry = response.data.expiry;
     })
}

The PHP

function dbs_timer_session(){
    if(empty($_COOKIE['dbs_timer'])){
        $t = time()+600;
        setcookie('dbs_timer', md5($t).'|'.$t, COOKIEPATH, COOKIE_DOMAIN);
    } else {
        $t = explode('|',$_COOKIE['dbs_timer']);
        $t = $t[1];
    }
    echo json_encode(['expiry' => $t]);
    wp_die();
}

EDIT 1 As requested, the wp_ajax actions

add_action( 'wp_ajax_nopriv_dbs_reservation', 'dbs_timer_session' );
add_action( 'wp_ajax_dbs_reservation', 'dbs_timer_session' );
  • 写回答

2条回答 默认 最新

  • dongpo3957 2016-06-27 22:18
    关注

    You were missing an argument for setcookie

     setcookie('dbs_timer', md5($t).'|'.$t, 'missing_expiry_time', COOKIEPATH, COOKIE_DOMAIN);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊