您可以使用cookies, window.name
,通过 url 作为查询字符串发送数据,或者通过网络存储 https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API.
在本例中,我将保存一个页面的数据并使用以下命令从另一页面读取数据:本地存储 https://hacks.mozilla.org/2009/06/localstorage/ - (specs http://nelsonslog.wordpress.com/2012/05/26/html5-localstorage/),以及以下方法:
- JSON.stringify() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
- JSON.parse() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
- WindowBase64.btoa() https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/btoa
- WindowBase64.atob() https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/atob
登录.html
function saveData(user, pass) {
var account = {
User: user,
Pass: pass
};
//converts to JSON string the Object
account = JSON.stringify(account);
//creates a base-64 encoded ASCII string
account = btoa(account);
//save the encoded accout to web storage
localStorage.setItem('_account', account);
}
索引.html
function loadData() {
var account = localStorage.getItem('_account');
if (!account) return false;
localStorage.removeItem('_account');
//decodes a string data encoded using base-64
account = atob(account);
//parses to Object the JSON string
account = JSON.parse(account);
//do what you need with the Object
fillFields(account.User, account.Pass);
return true;
}
通过 url 将对象从一个页面传递到另一个页面:请求参数 (search)
- Location https://developer.mozilla.org/en/docs/Web/API/Location
登录.html
function saveData(user, pass) {
var account = {
User: user,
Pass: pass
};
account = JSON.stringify(account);
account = btoa(account);
location.assign("index.html?a=" + account);
}
索引.html
function loadData() {
var account = location.search;
if (!account) return false;
account = account.substr(1);
//gets the 'a' parameter from querystring
var a = (/^a=/);
account = account.split("&").filter(function(item) {
return a.test(item);
});
if (!account.length) return false;
//gets the first element 'a' matched
account = account[0].replace("a=", "");
account = atob(account);
account = JSON.parse(account);
//do what you need with the Object
fillFields(account.User, account.Pass);
return true;
}
请参阅此处的扩展答案:https://stackoverflow.com/a/30070207/2247494 https://stackoverflow.com/a/30070207/2247494