如何在 JavaScript 中将变量从一个文件发送到另一个文件? [复制]

2024-01-19

我想从页面发送用户名和密码login.html to index.html。我怎样才能尽可能简单地做到这一点?以及如何对字符串进行编码,使其采用 URL 编码和 UTF-8?

Cheers


您可以使用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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 JavaScript 中将变量从一个文件发送到另一个文件? [复制] 的相关文章

随机推荐