I have a PHP script which sets a cookie called user. I need to be able to read the value from this cookie in javascript.
Can this even be done.
Thanks for any help you can provide.
There's no such thing as a "PHP cookie" or a "javascript cookie". There's just cookies, which you can access from PHP and Javascript. In JS, you'd use document.cookie
to access the raw cookie data. There's plenty of libraries which give you finer-grained access as well,
Take a look at document.cookie
.
Example from http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toUTCString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(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;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
Alternatively, if you use jQuery, there is a nice plugin: http://plugins.jquery.com/project/Cookie
您可以使用document.cookie
访问您的cookie检查此链接: http : //www.w3schools.com/js/js_cookies.asp
I tested it. You can read cookie which created with php.
You only need to add '/' (path)!!
setcookie("username", $username, $expire, '/');
Whether the cookie originates in JS or PHP should not matter. The cookie is stored for the domain, with a name and value. It does not contain information relating to how it originated.
Here is a plugin for accessing cookies in jQuery: http://plugins.jquery.com/project/Cookie
由于PHP是服务器端脚本并且JavaScript在浏览器中运行,因此您需要将cookie以隐藏的表单变量发送到浏览器,或者使用JavaScript中的AJAX调用从服务器获取它。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.