How to access PHP session variables from jQuery function in a .js file?

前端 未结 7 1157
轮回少年
轮回少年 2020-11-28 10:50

How to access PHP session variables from jQuery function in a .js file? In this code, I want to get \"value\" from a session variable

$(function() {
   $(\"#         


        
7条回答
  •  佛祖请我去吃肉
    2020-11-28 11:22

    This is strictly not speaking using jQuery, but I have found this method easier than using jQuery. There are probably endless methods of achieving this and many clever ones here, but not all have worked for me. However the following method has always worked and I am passing it one in case it helps someone else.

    Three javascript libraries are required, createCookie, readCookie and eraseCookie. These libraries are not mine but I began using them about 5 years ago and don't know their origin.

    createCookie = function(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    
    document.cookie = name + "=" + value + expires + "; path=/";
    }
    
    readCookie = function (name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
    }
    eraseCookie = function (name) {
       createCookie(name, "", -1);
    }
    

    To call them you need to create a small PHP function, normally as part of your support library, as follows:

    ";
     $s = $s.'createCookie('. '"'. $sessionVarible                 
     .'",'.'"'.$_SESSION[$sessionVarible].'"'. ',"1"'.')';
     $s = $s."";
     echo $s;
    }
    ?>
    

    So to use all you now have to include within your index.php file is

    $_SESSION["video_dir"] = "/video_dir/";
    createjavaScriptCookie("video_dir");
    

    Now in your javascript library.js you can recover the cookie with the following code:

    var videoPath = readCookie("video_dir") +'/'+ video_ID + '.mp4';
    

    I hope this helps.

提交回复
热议问题