前端实现跨页面传值的几种方式

一:利用url参数传递

//1:A页面设置url参数

$('#go_url').on('touchend',function () {
    var sss = "中国";
    window.location.href = encodeURI("demo2.html?name=" + sss + "&age=5000");
});

//2:B页面获取url参数

var url = window.location.search;
var urlResult = [];
var arrUrl = url.substr(1).split("&");
for (var j = 0; j < arrUrl.length; j++) {
    urlResult[j] = decodeURI(arrUrl[j].split("=")[1]);
}
$('.name').text('名称:' + urlResult[0]);
$('.age').text('数量:' + urlResult[1]);
(注:上面用了 encodeURI编码,decodeURI解码来解决中文乱码的问题

二:利用缓存传递

//1:A页面设置参数到缓存

$('button').on('touchend',function () {
    var username = $('#username').val();
    var userage = $('#userage').val();
    var arrLocalStorage = [username, userage];

    //存储,IE6~7 cookie 其他浏览器HTML5本地存储
    if (window.localStorage) {
        localStorage.setItem("localName", arrLocalStorage);
    } else {
        Cookie.write("localName", arrLocalStorage);
    }
});

//2:B页面获取缓存值

var StoreDate = window.localStorage ? localStorage.getItem("localName") : Cookie.read("localName");
var arrStoreDate = StoreDate.split(",");
for  (var i = 0; i < arrStoreDate.length; i++) {
    var liHtml = "
  • " + arrStoreDate[i] + "
  • "
    ; $('.list').append(liHtml); }

    你可能感兴趣的:(前端实现跨页面传值的几种方式)