javascript 如何使用 JQuery 将数据从一个 HTML 页面传递到另一个 HTML 页面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11508818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:27:47  来源:igfitidea点击:

How to pass data from one HTML page to another HTML page using JQuery?

javascriptjqueryajaxjsonjquery-mobile

提问by AGE

I have two HTML pages that work in a parent-child relationship in this way:

我有两个以这种方式在父子关系中工作的 HTML 页面:

The first one has a button which does two things: First it requests data from the database via an AJAX call. Second it directs the user to the next page with the requested data, which will be handled by JavaScript to populate the second page.

第一个按钮有两个作用:首先,它通过 AJAX 调用从数据库请求数据。其次,它将用户引导到具有请求数据的下一页,这些数据将由 JavaScript 处理以填充第二页。

I can already obtain the data via an ajax call and put it in a JSON array:

我已经可以通过 ajax 调用获取数据并将其放入 JSON 数组中:

$.ajax({
    type: "POST",
    url: get_data_from_database_url,
    async:false,
    data: params,
    success: function(json)
    {
        json_send_my_data(json);
    }
});

function json_send_my_data(json)
{
    //pass the json object to the other page and load it
}

I assume that on the second page, a "document ready" JavaScript function can easily handle the capture of the passed JSON object with all the data. The best way to test that it works is for me to use alert("My data: " + json.my_data.first_name);within the document ready function to see if the JSON object has been properly passed.

我假设在第二页上,“文档就绪”JavaScript 函数可以轻松地处理对传递的 JSON 对象以及所有数据的捕获。测试它是否有效的最佳方法是我alert("My data: " + json.my_data.first_name);在文档就绪函数中使用它来查看 JSON 对象是否已正确传递。

I simply don't know a trusted true way to do this. I have read the forums and I know the basics of using window.location.urlto load the second page, but passing the data is another story altogether.

我只是不知道一个值得信赖的真正方法来做到这一点。我已经阅读了论坛,我知道window.location.url用于加载第二页的基础知识,但传递数据完全是另一回事。

回答by Guilherme Nascimento

session cookie may solve your problem.

会话 cookie 可能会解决您的问题。

On the second page you can print directly within the cookies with Server-Script tag or site document.cookie

在第二页上,您可以使用 Server-Script 标签或站点 document.cookie 直接在 cookie 中打印

And in the following section converting Cookies in Json again

并在以下部分再次转换 Json 中的 Cookies

How about?

怎么样?

回答by Matt

You have two options I think.

我认为你有两个选择。

1) Use cookies - But they have size limitations.

1) 使用 cookie - 但它们有大小限制。

2) Use HTML5 web storage.

2) 使用HTML5 网络存储

The next most secure, reliable and feasible way is to use server side code.

下一个最安全、可靠和可行的方法是使用服务器端代码。

回答by Matt

Disclaimer: This is terrible, but here goes:

免责声明:这很糟糕,但这里是:

First, you will need this function (I coded this a while back). Details here: http://refactor.blog.com/2012/07/13/porting-javas-getparametermap-functionality-to-pure-javascript/

首先,您将需要此函数(我不久前对此进行了编码)。详情请见:http: //refactor.blog.com/2012/07/13/porting-javas-getparametermap-functionality-to-pure-javascript/

It converts request parameters to a json representation.

它将请求参数转换为 json 表示。

function getParameterMap () {
    if (window.location.href.indexOf('?') === (-1)) {
        return {};
    }
    var qparts = window.location.href.split('?')[1].split('&'),
        qmap   = {};
    qparts.map(function (part) {
        var kvPair = part.split('='),
            key    = decodeURIComponent(kvPair[0]),
            value  = kvPair[1];

        //handle params that lack a value: e.g. &delayed=
        qmap[key] = (!value) ? '' : decodeURIComponent(value);
    });
    return qmap;
}

Next, inside your success handler function:

接下来,在您的成功处理函数中:

success: function(json) {
    //please really convert the server response to a json
    //I don't see you instructing jQuery to do that yet!
    //handleAs: 'json'

    var qstring = '?';
    for(key in json) {
        qstring += '&' + key + '=' + json[key];
        qstring = qstring.substr(1); //removing the first redundant &
    }
    var urlTarget = 'abc.html';
    var urlTargetWithParams = urlTarget + qstring;

    //will go to abc.html?key1=value1&key2=value2&key2=value2...
    window.location.href = urlTargetWithParams;
}

On the next page, call getParameterMap.

在下一页,调用 getParameterMap。

var jsonRebuilt = getParameterMap();
//use jsonRebuilt 

Hope this helps (some extra statements are there to make things very obvious). (And remember, this is most likely a wrong way of doing it, as people have pointed out).

希望这会有所帮助(有一些额外的陈述可以使事情变得非常明显)。(请记住,正如人们所指出的那样,这很可能是一种错误的做法)。

回答by Roman Goyenko

Here is my post about communicating between two html pages, it is pure javascript and it uses cookies: Javascript communication between browser tabs/windows

这是我关于两个 html 页面之间通信的帖子,它是纯 javascript 并且使用 cookie: 浏览器选项卡/窗口之间的 Javascript 通信

you could reuse the code there to send messages from one page to another.

您可以重用那里的代码将消息从一个页面发送到另一个页面。

The code uses polling to get the data, you could set the polling time for your needs.

该代码使用轮询来获取数据,您可以根据需要设置轮询时间。

回答by Jasper

Warning: This will only work for single-page-templates, where each pseudo-page has it's own HTML document.

警告:这仅适用于单页模板,其中每个伪页都有自己的 HTML 文档。

You can pass data between pages by using the $.mobile.changePage()function manually instead of letting jQuery Mobile call it for your links:

您可以$.mobile.changePage()手动使用该函数在页面之间传递数据,而不是让 jQuery Mobile 为您的链接调用它:

$(document).delegate('.ui-page', 'pageinit', function () {
    $(this).find('a').bind('click', function () {
        $.mobile.changePage(this.href, {
            reloadPage : true,
            type       : 'post',
            data       : { myKey : 'myVal' }
        });
        return false;
    });
});

Here is the documentation for this: http://jquerymobile.com/demos/1.1.1/docs/api/methods.html

这是此文档:http: //jquerymobile.com/demos/1.1.1/docs/api/methods.html

You can simply store your data in a variable for the next page as well. This is possible because jQuery Mobile pages exist in the same DOM since they are brought into the DOM via AJAX. Here is an answer I posted about this not too long ago: jQuery Moblie: passing parameters and dynamically load the content of a page

您也可以简单地将数据存储在下一页的变量中。这是可能的,因为 jQuery Mobile 页面存在于同一个 DOM 中,因为它们是通过 AJAX 引入 DOM 的。这是我不久前发布的一个答案:jQuery Moblie:传递参数并动态加载页面的内容