简体   繁体   English

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

[英]Transfer data from one HTML file to another

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测试.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

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, eg 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. PS。 i'm an non-native english speaker, will you please correct my message, if necessary我是非英语母语人士,如有必要,请您更正我的信息

The old fashioned way of setting a global variable that persist between pages is to set the data in a Cookie.设置在页面之间持续存在的全局变量的老式方法是在 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+).现代方法是使用本地存储,它具有良好的浏览器支持(IE8+、Firefox 3.5+、Chrome 4+、Android 2+、iPhone 2+)。 Using localStorage is as easy as using an array:使用 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.您还可以附加事件处理程序以侦听更改,尽管事件 API 在浏览器之间略有不同。 More on the topic.更多关于这个话题。

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. Html 页面通过 HTTP 协议传递给浏览器,这是一种“无状态”协议。 If you still needed to pass values in between pages, there could be 3 approaches:如果您仍然需要在页面之间传递值,可能有 3 种方法:

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

With the Javascript localStorage class, 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.使用 Javascript localStorage类,您可以使用浏览器的默认本地存储来保存(键、值)对,然后使用键在您需要的任何页面上检索这些值。 Example - Pageone.html -示例 - Pageone.html -

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

Pagetwo.html - Pagetwo.html -

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

you can simply send the data using window.location.href first store the value to send from testing.html in 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这是通过获取请求发送的

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);

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嗨,我要把这个留在这里,因为限制,我无法发表评论,但我发现 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 .我知道五年后帖子的所有者不会发现它有任何重要性,但这是为将来可能遇到的人准备的。

<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. jQuery 是一个 js 库,它简化了它的编程。 So I recommend to use jQuery rathar then js.所以我推荐使用 jQuery rathar 然后 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.在这里,我只是在提交按钮单击事件上获取输入元素(id = name)的值,然后加载所需的页面(next.html),如果加载函数成功执行,我将调用一个函数,它将数据放在所需的位置。

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

The following is a sample code to pass values from one page to another using html.以下是使用 html 将值从一个页面传递到另一个页面的示例代码。 Here the data from page1 is passed to page2 and it's retrieved by using javascript.在这里,来自 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>

I coded the answers from Alex Fitiskin, and added a bit of extra code.我对 Alex Fitiskin 的答案进行了编码,并添加了一些额外的代码。 I added a parameter to the onLoad function to get the form's submit event, and prevent it's default behaviour first.我在 onLoad 函数中添加了一个参数来获取表单的提交事件,并首先阻止它的默认行为。

Here's the code:这是代码:

test.html测试.html

<html>
<head>
    <script language="javascript" type="text/javascript" src="test.js"></script>
</head>
<body>
    <form name="form1" action="next.html" method="get" onsubmit="return testJS(event)">
        name:<input type="text" id="name" name="n">
        <input type="submit" value="next">
        <!-- <button type="button" id="print" onClick="testJS()"> Print </button> //Button not needed anymore -->
    </form>
</body>
</html>

next.html下一个.html

<head>
    <script language="javascript" type="text/javascript" src="test.js"></script>
</head>
<body>
    <form name="form1" action="next.html" method="get">
        <table>
            <tr>
                <td id="here">test</td>
            </tr>
        </table>
    </form>
</body>
</html>

test.js测试.js

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

    document.location.href = url;
}

function onLoad() {
    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;
}

window.onload = onLoad;

This way the onload function will be replaced with the custom onLoad function, and the form will not be submitted the default way, but instead using the code inside the testJS function.这样onload函数就会被自定义的onLoad函数代替,表单不会按默认方式提交,而是使用testJS函数里面的代码。

Avoid localstorage use as data are not safe with get method.避免使用本地存储,因为 get 方法不安全。 Best option is to use script set to module and then export & import data via 2 js files to html file.最好的选择是使用脚本设置为模块,然后通过 2 个 js 文件将数据导出和导入到 html 文件。 Variable value can be passed between pages using module method.变量值可以使用模块方法在页面之间传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从一个 HTML 页面到另一个页面的数据传输 - Data transfer from one HTML page to another 帮助从一个HTML表单到另一个HTML表单的数据传输/存储 - Help with data transfer/storage from one HTML form to another 如何使用javascript将数据从一个html页面传输到另一页面 - how to transfer data from one html page to another using javascript 将数据从一个html文件填充到另一个 - Populate data from one html file to another 将数据从一页传输到另一页 - Transfer data from one page to another 将一行数据从一个 object 转移到另一个 - Transfer a row of data from one object to another 使用AngularJS服务将数据从一个html传输到另一个html(控制器之间的数据共享) - Transfer data from one html to another using AngularJS services (data share between controllers) 如何在不使用表单和输入标签的情况下将数据从一个 html 页面传输到另一个页面 - how to transfer data from one html page to another without using forms and input tags 如何仅使用HTML5和JavaScript将文件从本机传输到vpn中的另一个文件 - How to transfer a file from my machine to another one in the vpn using only HTML5 and JavaScript 使用 JavaScript 将 HTML 元素从一个列表传输到另一个列表 - Transfer HTML elements from one list to another with JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM