doufei7464 2016-07-30 20:30 采纳率: 0%
浏览 15

如何设置要创建onclick事件的php cookie [重复]

This question already has an answer here:

I'm using javascript to trigger my cookies and I've been told that the most reliable method to set cookies is to create them on the server side using php...

I already tested this code, but it creates the cookie on page load and I need it to be set only when the user clicks a link:

    <a href="<?php 
if (!isset($_COOKIE['my_test_cookie'])) {   
ob_start();
setcookie("my_test_cookie", "1", time()+ (86400 * 90), "/");
ob_end_flush();
}?>" onClick="javascript:HideContent('div3');">Create Cookie</a>

Is it possible to build the cookie on php and only create him onclick event?

eg: < href="#" onclick="call_the_php_function_where_we_setup_the_cookie_variables();">click here to create the cookie</a>

</div>
  • 写回答

1条回答 默认 最新

  • dsij89625 2016-07-30 20:32
    关注

    PHP is run on the server before the page is ever seen by the client browser. There isn't any way to get PHP code to run after the page has been sent to the client.

    The only solution is going to be to use AJAX in the background when the button is clicked to load a php page that does what you want.

    For example, you could set up your page to run something like this when the button is clicked:

    var req = new XMLHttpRequest();
    req.addEventListener("load", function() {
        console.log(this.responseText);
    });
    req.open("GET", "http://yoursite.com/path_to_cookie_setter_page");
    req.send();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大