dongyu2047 2016-11-17 08:32
浏览 78

从jQuery设置cookie并从php读取的正确方法

I've tried to read the cookie values in PHP that are set via jQuery. But it's not read in first time page load. But I saw it's already set by the jQuery and can read the same value from the jquery.

When trying to read that cookie value from PHP it's not display the value when page rendered first time. But again refresh the page it's give the value from php.(I need to refresh page 2 time to get the correct value)

I used both head tag and onload method to place the setCookie() function. But result was same.

I used this jQuery library to write cookie.

Here's code I used to read and write the cookie.

<?php
    if (!isset($_SESSION)) {
        session_start();
    }
    ?>
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
            <style>
                body{
                    background: #666666;
                }
            </style>
            <script src="js/jquery.min.js" type="text/javascript"></script>
            <script src="js/jquery.cookie.js" type="text/javascript">/script>
            <script>
                setCookie();
                function setCookie() {
                    console.log('on Load');
                    var data_spl = $(location).attr('href').split('#?camlist=')[1];
                    if (data_spl != undefined) {
                        var len = data_spl.split(',').length;
                        $.cookie("len", len);
                        console.log($.cookie("len"));
                    } else {
                        console.log('undefined');
                    }
                }
            </script>
        </head>
        <body>           
            <?php
            for ($i = 0; $i < 100; $i++) {
                echo "<script>console.log('START');</script>";
                echo "<script>console.log('" . $_COOKIE['len'] . "');</script>";
                echo $_COOKIE['len'];
                echo "<script>console.log('END');</script>";
            }

            echo "WIDTH & HEIGHT :" . $_SESSION['width_x'] . "-" . $_SESSION['height_y'];
            ?>        
        </body>
    </html>

EDITED:

I used another php page to set session value that are came from java script and call that page via jQuery like shown in bellow.

var len = $(location).attr('href').split('#?data=')[1].split(',').length;
$.post('set_session.php', {params: len}, function (retparams) {
      if (retparams.has) {
         console.log('sucessfuly sent the paramlen!');             
      } else {
         alert("can't read camarauids for grid making");
      }
}, 'retparams');

set_session.php

<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
    $_SESSION['urllen'] = 0;
}
if (isset($_POST['params'])) {
    $_SESSION['urllen'] = $_POST['params'];
    echo json_encode(array('retparams' => 'has'));
    echo json_encode(array('datalen' => $_SESSION['urllen']));
} else {
    echo json_encode(array('retparams' => 'error'));
}
?>

Then I try to read the session value ($_SESSION['urllen']) from index.php page. But it's also same as the above.(I need to refresh page one more time to get the correct value that are set from the jQuery post function.)

  • 写回答

2条回答 默认 最新

  • doulang9953 2016-11-17 09:15
    关注

    You could check this with ajax. Here is a simple example:

    <?php
      if(isset($_GET["checkIfLoggedIn"]) && boolval($_GET["checkIfLoggedIn"]) === true) {
        header("Content-Type: text/json");
        die(json_encode(array("isLoggedIn" => $_COOKIE["isLoggedIn"])));
        exit();
      } else {
        var_dump($_COOKIE);
      }
    ?>
    
    <html>
    
      <head>
        <script type="text/javascript" src="jquery-3.1.1.min.js"></script>
        <script type="text/javascript" src="js.cookie.js"></script>
      </head>
    
      <body>
        <script type="text/javascript">
          function checkIfLoggedIn() {
            console.log("checking...");
    
            jQuery.post("?checkIfLoggedIn=1", function(data) {
              if(data.isLoggedIn == true) {
                alert("Logged im.");
              } else {
                alert("NOT logged in!");
              }
            });
          }
        </script>
    
        <a href="#" onclick="Cookies.set('isLoggedIn', 'true'); checkIfLoggedIn(); return false;">Set logged in to true</a><br/>
        <a href="#" onclick="Cookies.set('isLoggedIn', 'false'); checkIfLoggedIn(); return false;">Set logged in to false</a>
    
      </body>
    
    </html>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度