开发者

Is it possible to a create session variable in JavaScript?

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 JavaScript function with PHP.

I'm just a beginner in JavaScript so please also refer 开发者_Go百科me some good books.


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)


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.");
    }
};


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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜