javascript 如何读取/写入本地 file:/// HTML 文档的 cookie?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12992494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read/write cookies for local file:/// HTML document?
提问by ?mega
How can I read/write cookies for local file:///
HTML document using Javascript or jQuery?
如何file:///
使用 Javascript 或 jQuery读取/写入本地HTML 文档的cookie ?
I tried this one >>
我试过这个 >>
function setCookie(c_name, value, exdays)
{
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) +
((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name)
{
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++)
{
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name)
{
return unescape(y);
}
}
}
But it does not work.
但它不起作用。
回答by NilsB
It depends on your browser. Chrome e.g. doesn't allow cookies for local files. see: where cookie saved for local HTML file
这取决于您的浏览器。例如,Chrome 不允许本地文件使用 cookie。请参阅:为本地 HTML 文件保存 cookie 的位置
回答by Harly Walsh
This will work locally
这将在本地工作
// save data value
localStorage.setItem("name", "John");
// retrieve data value
var name = localStorage.getItem("name");
回答by uzername_not_found
try this one:
试试这个:
https://github.com/carhartl/jquery-cookie
https://github.com/carhartl/jquery-cookie
If you need multiple values stored in it try this:
如果您需要在其中存储多个值,请尝试以下操作:
回答by aydow
As an alternative to loading the page from file, you can run a webserver and load the page from localhost. Apache comes with OSX and Ubuntu. Once you have set that up you will be able to use cookies on the local page.
作为从文件加载页面的替代方法,您可以运行网络服务器并从本地主机加载页面。Apache 带有 OSX 和 Ubuntu。设置完成后,您就可以在本地页面上使用 cookie。