Is it possible to a create session variable in JavaScript?

后端 未结 5 1487
情歌与酒
情歌与酒 2021-01-05 09:50

Is it possible to create and update a session variable in JavaScript? Just like in PHP as I start sessions and initialize session variable.

I\'m using some JavaScrip

相关标签:
5条回答
  • 2021-01-05 10:13

    The usual meaning of the term "Session variable" is: "Some data stored on the server, which is associated with a user's session via a token".

    Assuming you are talking about client side JavaScript, then the short answer is "no" as it runs on the wrong computer.

    You could use JS to make an HTTP request to the server, and have a server side programme store data in a session variable.

    You could also use JS to store data in a cookie (and not set an expiry time so it expires at the end of the browser session)

    0 讨论(0)
  • 2021-01-05 10:13

    Well, taking a look at how sessions work, no, they cannot be created with javascript. You can, though, make an AJAX request to your PHP file to set one.

    PHP:

    <?php
    session_start(); 
    $_SESSION['mySession'] = 1;
    ?>
    

    JS:

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "session_maker.php", true);
    
    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
            alert("Done! Session created.");
        }
    };
    
    0 讨论(0)
  • 2021-01-05 10:15

    No, session state is server-side. You can, however, create cookies that PHP can read.

    0 讨论(0)
  • 2021-01-05 10:19

    There are a number of ways of recording state in Javascript - none of which are particularly great / cross-browser, but there you go.

    You can set and get cookies - http://www.quirksmode.org/js/cookies.html

    Window.name storage (sessionvars) - http://www.thomasfrank.se/sessionvars.html - this is a very cool hack, but probably not a great idea to use for anything important

    HTML5 local storage - http://diveintohtml5.ep.io/storage.html

    Server-side is probably the way to go here, but client-side you have a few options.

    0 讨论(0)
  • 2021-01-05 10:21

    You could use the js via the ajax way from/to load/post to a php script and write your session control method into this php script file.

    You could try the jQuery's $.ajax() method, I guess it is the easy way to made it on the front-end script.

    0 讨论(0)
提交回复
热议问题