将数据从一个 HTML 文件传输到另一个

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17502071/
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-08-29 10:50:01  来源:igfitidea点击:

Transfer data from one HTML file to another

javascripthtml

提问by newbie

I'm new to HTML and JavaScript, what I'm trying to do is from an HTML file I want to extract the things that set there and display it to another HTML file through JavaScript.

我是 HTML 和 JavaScript 的新手,我想要做的是从一个 HTML 文件中提取设置在那里的内容并通过 JavaScript 将其显示到另一个 HTML 文件中。

Here's what I've done so far to test it:
testing.html

这是我到目前为止所做的测试:
testing.html

<html>
<head>
   <script language="javascript" type="text/javascript" src="asd.js"></script>
</head>

<body>

<form name="form1" action="next.html" method="get">
name:<input type ="text" id="name" name="n">
<input type="submit" value="next" >
<button type="button" id="print" onClick="testJS()"> Print </button>
</form>

</body>
</html>

next.html

下一个.html

<head>
   <script language="javascript" type="text/javascript" src="asd.js"></script>
</head>

<body>

<form name="form1" action="next.html" method="get">
<table>
    <tr>
        <td id="here">test</td>
    </tr>
</table>
</form>

</body>
</html>

asd.js

asd.js

function testJS()
{

var b = document.getElementById('name').value

document.getElementById('here').innerHTML = b;

}

test.html-> ads.js(will extract value from the test.html and set to next.html) -> next.html

test.html-> ads.js(将从 test.html 中提取值并设置为 next.html)->next.html

回答by Alex Fitiskin

Try this code: In testing.html

试试这个代码:在 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;
}

And in next.html:

在 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;
}

Description: javascript can't share data between different pages, and we must to use some solutions, e.g. URL get params (in my code i used this way), cookies, localStorage, etc. Store the name parameter in URL (?name=...) and in next.html parse URL and get all params from prev page.

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

PS. i'm an non-native english speaker, will you please correct my message, if necessary

附注。我的母语不是英语,如有必要,请您更正我的信息

回答by Lie Ryan

The old fashioned way of setting a global variable that persist between pages is to set the data in a Cookie. The modern way is to use Local Storage, which has a good browser support (IE8+, Firefox 3.5+, Chrome 4+, Android 2+, iPhone 2+). Using localStorage is as easy as using an array:

设置在页面之间持续存在的全局变量的老式方法是在 Cookie 中设置数据。现代方法是使用本地存储,它具有良好的浏览器支持(IE8+、Firefox 3.5+、Chrome 4+、Android 2+、iPhone 2+)。使用 localStorage 就像使用数组一样简单:

localStorage["key"] = value;

... in another page ...
value = localStorage["key"];

You can also attach event handlers to listen for changes, though the event API is slightly different between browsers. More on the topic.

您还可以附加事件处理程序来侦听更改,但浏览器之间的事件 API 略有不同。更多关于这个话题。

回答by Shreyas

Assuming you are talking about this js in browser environment (unlike others like nodejs), Unfortunately I think what you are trying to do isn't possible simply because this is not the way it is supposed to work.

假设你在浏览器环境中谈论这个 js(不像其他人像 nodejs),不幸的是我认为你试图做的事情是不可能的,因为这不是它应该的工作方式。

Html pages are delivered to the browser via HTTP Protocol, which is a 'stateless' protocol. If you still needed to pass values in between pages, there could be 3 approaches:

Html 页面通过 HTTP 协议传送到浏览器,这是一种“无状态”协议。如果您仍然需要在页面之间传递值,可能有 3 种方法:

  1. Session Cookies
  2. HTML5 LocalStorage
  3. POST the variable in the url and retrieve them in next.html via windowobject
  1. 会话 Cookie
  2. HTML5 本地存储
  3. 在 url 中发布变量并通过window对象在 next.html 中检索它们

回答by Tripathi29

you can simply send the data using window.location.hreffirst store the value to send from testing.htmlin the script tag, variable say

您可以简单地使用window.location.href首先将要发送的值存储testing.html在脚本标记中来发送数据,变量说

<script> 
  var data = value_to_send
  window.loaction.href="next.htm?data="+data
</script>

this is sending through a get request

这是通过获取请求发送的

回答by Harish Anantharaman

With the Javascript localStorageclass, you can use the default local storage of your browser to save (key,value) pairs and then retrieve these values on whichever page you need using the key. Example - Pageone.html -

使用 Javascript localStorage类,您可以使用浏览器的默认本地存储来保存 (key,value) 对,然后在您需要使用密钥的任何页面上检索这些值。示例 - Pageone.html -

<script>
    localStorage.setItem("firstname", "Smith");
</script>  

Pagetwo.html -

Pagetwo.html -

<script>
    var name=localStorage.getItem("firstname");
</script>  

回答by Anjula S.

HI im going to leave this here cz i cant comment due to restrictions but i found AlexFitiskin's answer perfect, but a small correction was needed

嗨,我要离开这里 cz 由于限制,我无法发表评论,但我发现 AlexFitiskin 的回答很完美,但需要稍作修正

document.getElementById('here').innerHTML = data.name; 

This needed to be changed to

这需要更改为

document.getElementById('here').innerHTML = data.n;

I know that after five years the owner of the post will not find it of any importance but this is for people who might come across in the future .

我知道五年后,帖子的所有者不会发现它有任何重要意义,但这是为将来可能会遇到的人准备的。

回答by prashant kute

I use this to set Profile image on each page.

我用它在每个页面上设置个人资料图像。

On first page set value as:

在第一页上将值设置为:

localStorage.setItem("imageurl", "ur image url");

or on second page get value as :

或在第二页上获取值:

var imageurl=localStorage.getItem("imageurl");
document.getElementById("profilePic").src = (imageurl);

回答by Codemaker

The following is a sample code to pass values from one page to another using html. Here the data from page1 is passed to page2 and it's retrieved by using javascript.

以下是使用 html 将值从一个页面传递到另一个页面的示例代码。这里来自 page1 的数据被传递到 page2 并使用 javascript 检索它。

1) page1.html

1) page1.html

<!-- Value passing one page to another 
     Author: Codemaker
-->
<html>
    <head>
        <title> Page 1 - Codemaker</title>
    </head>
    <body>
        <form method="get" action="page2.html">
            <table>
                <tr>
                    <td>First Name:</td>
                    <td><input type=text name=firstname size=10></td>
                </tr>
                <tr>
                    <td>Last Name:</td>
                    <td><input type=text name=lastname size=10></td>
                </tr>
                <tr>
                    <td>Age:</td>
                    <td><input type=text name=age size=10></td>
                </tr>
                <tr>
                    <td colspan=2><input type=submit value="Submit">
                    </td>
                </tr>
            </table>
        </form>
    </body>
</html>

2) page2.html

2) page2.html

<!-- Value passing one page to another 
     Author: Codemaker
-->

<html>
    <head>
        <title> Page 2 - Codemaker</title>
    </head>
    <body>
        <script>
            function getParams(){
                var idx = document.URL.indexOf('?');
                var params = new Array();
                if (idx != -1) {
                    var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
                    for (var i=0; i<pairs.length; i++){
                        nameVal = pairs[i].split('=');
                        params[nameVal[0]] = nameVal[1];
                    }
                }
                return params;
            }
            params = getParams();
            firstname = unescape(params["firstname"]);
            lastname = unescape(params["lastname"]);
            age = unescape(params["age"]);
            document.write("firstname = " + firstname + "<br>");
            document.write("lastname = " + lastname + "<br>");
            document.write("age = " + age + "<br>");
        </script>
    </body>
</html>

回答by myk.

<html>
<head>
<script language="javascript" type="text/javascript" scr="asd.js"></script>
</head>

<body>

<form name="form1" action="#" method="get">
name:<input type ="text" id="name" name="n">
<input type="submit" value="next" >
<button type="button" id="print" onClick="testJS()"> Print </button>
</form>

</body>

client side scripting

客户端脚本

function testJS(){
var name = jQuery("#name").val();
jQuery.load("next.html",function(){
jQuery("#here").html(name);
});
}

jQuery is a js library and it simplifies its programming. So I recommend to use jQuery rathar then js. Here I just took value of input elemnt(id = name) on submit button click event ,then loaded the desired page(next.html), if the load function executes successfully i am calling a function which will put the data in desired place.

jQuery 是一个 js 库,它简化了它的编程。所以我建议先使用 jQuery rathar 然后使用 js。在这里,我只是在提交按钮单击事件时获取输入元素(id = name)的值,然后加载所需的页面(next.html),如果加载函数成功执行,我将调用一个将数据放在所需位置的函数。

jquery load function http://api.jquery.com/load/

jquery 加载函数http://api.jquery.com/load/