Web前端不同页面间传值可以使用 cookies、localStorage 和 sessionStorage 等本地存储。
但是,今天我们尝试使用 url 查询,假设我们要传递字符串 str 到 modify.html 页面:
var str = "name=Bob Chen&gender=男&date=1998/04/26&idNumber=430523000000000000&telNumber=13400007511&email=2099367442@qq.com&city=北京";
1、使用encodeURIComponent编码:
location.href = "modify.html?" + encodeURIComponent(str);
url格式如下:
domain:port/path/modify.html?name%3DBob%20Li%26gender%3D%E7%94%B7%26date%3D1998%2F04%2F26%26idNumber%3D430523000000000008%26telNumber%3D13400007511%26email%3D2099367442%40qq.com%26city%3D%E5%8C%97%E4%BA%AC
2、使用encodeURI编码:
location.href = "modify.html?" + encodeURI(str);
url格式如下:
domain:port/path/modify.html?name=Bob%20Chen&gender=男&date=1998/04/26&idNumber=430523000000000000&telNumber=13400007511&email=2099367442@qq.com&city=北京
通过url查询传值后,接下来我们需要解析url,我们为 jQuery 对象添加新方法 parseUrl 来解析url查询:
(function($) { $.parseUrl = function() { var paramObj = {}, paramsArr = decodeURIComponent(location.href).split("?")[1].split("#")[0].replace(/+/g, " ").split("&"), i = 0, len = paramsArr.length; for (; i < len; i++) { var param = paramsArr[i].split("=")[0].trim(), value = paramsArr[i].split("=")[1].trim(); if (param == "date") { paramObj[param] = value.replace(///g, "-"); } else { paramObj[param] = value; } } return paramObj; } })(jQuery);
然后,我们就可以通过 paramObj 的属性来访问传递的数据了:
var paramObj = $.parseUrl(); console.log(paramObj['name']);