首页 > 解决方案 > 如何创建将数据从一个本地站点传输到另一个站点的 JS

问题描述

情况是这样的:您在网站 A 的一个字段中输入文本并按下按钮,在网站 B 中按下该按钮会显示输入的文本。我曾尝试使用 localStorage,但没有运气。有什么帮助吗?

标签: javascripthtml

解决方案


试试这个代码:在 testing.html

function testJS() {
    var b = document.getElementById('name').value,
        url = 'http://path_to_your_html_files/next.html?name=' + encodeURIComponent(b);

    document.location.href = url;
}

在 next.html 中:

window.onload = function () {
    var url = document.location.href,
        params = url.split('?')[1].split('&'),
        data = {}, tmp;
    for (var i = 0, l = params.length; i < l; i++) {
         tmp = params[i].split('=');
         data[tmp[0]] = tmp[1];
    }
    document.getElementById('here').innerHTML = data.name;
}

说明:javascript不能在不同页面之间共享数据,我们必须使用一些解决方案,例如URL get params(在我的代码中我使用这种方式),cookies,localStorage等。将name参数存储在URL中(?name = ...) 并在 next.html 中解析 URL 并从上一页获取所有参数。

PS。我是非英语母语人士,如有必要,请您更正我的信息


推荐阅读