开发者

Problem with Javascript & Cookies

Using Javascript, I want to create a cookie with the value of an input field with the id "username" everytime a button is pressed. I then want to read that cookie and display it on the website. Though I just tried this to test my knowledge of cookies, I would now like to know the solution to this problem, because my code does not work.

I am gonna be using these two functions from elated.com:

function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
var cookie_string = name + "=" + escape ( value );

if ( exp_y )
{
   var expires = new Date ( exp_y, exp_m, exp_d );
   cookie_string += "; expires=" + expires.toGMTString(开发者_Go百科);
}

if ( path )
    cookie_string += "; path=" + escape ( path );

if ( domain )
    cookie_string += "; domain=" + escape ( domain );

if ( secure )
    cookie_string += "; secure";

document.cookie = cookie_string;




function get_cookie ( cookie_name )
{
var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

 if ( results )
     return ( unescape ( results[2] ) );
else
    return null;
}

When the button is pressed this function is going to run:

function Register()
{
var username = document.getElementById("username").value; //Read the input value
set_cookie("username", username, 2012, 12, 23); //Set the cookie
document.write(get_cookie("username")); //Read the cookie
}

Whenever I try to run this, the get_cookie function returns null. This means that it's at least being run successfully, but not finding any cookie named "username", even though I just created it. Can anybody help?


You say you're using Chrome. Chrome (and Chromium) don't allow setting or accessing cookies on local pages, as a deliberate decision over security concerns (see http://code.google.com/p/chromium/issues/detail?id=535#c3). The code you posted does work if put onto a server and sent out, but won't behave correctly if you open the page from your local system as a file:// URL. That's also why the jsfiddle works.

Some other browsers do allow cookies in local pages, so if you're looking to experiment with JavaScript and cookies locally you might be better trying one of those. Firefox allows them with the expected behaviour, although they have considered changing it and might do in future. Chrome also has a command-line flag --enable-file-cookies that you could use while testing, but they don't recommend it for everyday use.

You could also put your page onto a server and test there. Either one of the free hosting services or an instance of Apache or similar on your local computer would work. The important part is just that the page is accessed over HTTP.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜