开发者

Read and write cookies

I have a javascript file linked to a PHP page which has a value that needs be saved for when a form is submitted and the page is refreshed.

Is there a simple way to set cookies similar to the method in PHP.

setcookie("MovementDate", $MovementDate, time()+3600);  

Everything I have found is very complex and can't seem to get to work.

Also reading set cookies is currently an issue. From my searches I came up with this method however it's not working.

function readCookie(name)开发者_如何学Python {
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);
}

}

var movement = readCookie(MovementDate);
document.write(movement);


If you're already comfortable with using PHP, you can use PHPjs:

For setting, use the setcookie function.

For reading, use the use the runkit_superglobals function. This will give you access to the the $_COOKIE superglobal using the exact same methods as PHP.

Example:

// Setting
// setcookie uses seconds but the JS Date object returns milliseconds,
// so we need to divide by 1000
setcookie("foo", "bar", (new Date().getTime() / 1000) + 3600);

// Reading
runkit_superglobals();    
alert($_COOKIE["foo"]); // alerts "bar"


When calling readCookie, the argument needs to be a string. Change your second to last line to this:

var movement = readCookie("MovementDate");
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜