通过 JavaScript 将变量从一个 html 页面传递到另一个页面
我有两页 - 第 1 页"和第 2 页".在第 1 页上有一个文本框,其值为例如100 和最后一个按钮.
I have two pages - "page 1" and "page 2". On page 1 there's an text-box with a value of e.g. 100 and a button at the end.
通过按下按钮,我希望 javascript 将文本框的值保存在全局 (?) 变量中并跳转到第 2 页.使用window.onload"我想要第二个 Javascript 函数来提醒保存在第 1 页的值.
By pressing the button I want javascript to save the value of the textbox in a global (?) variable and jump to page 2. With "window.onload" I want a second Javascript-function to alert the value saved at page1.
这是我的 Javascript 代码:
Here's my Javascript code:
<script type="text/javascript">
var price; //declare outside the function = global variable ?
function save_price(){
alert("started_1"); //just for information
price = document.getElementById('the_id_of_the_textbox').value;
alert(price); //just for information
}
<script type="text/javascript">
function read_price(){
alert("started_2");
alert(price);
}
在第 1 页"我有这个发送按钮:
On "page 1" I have this send-Button with:
<input class="button_send" id="button_send" type="submit" value="Submit_price" onclick="save_price();"/>
它启动 Javascript 功能并将我正确重定向到我的 page2.
It starts the Javascript function and redirects me correctly to my page2.
但是在第二页上:
window.onload=read_price();
我总是得到全局变量价格的未定义"值.
I always get an "undefined" value of the global variable price.
我已经阅读了很多关于这些全局变量的内容.例如.在此页面:全局变量的问题..但我无法让它工作......
I've read a lot about those global variables. E.g. at this page: Problem with global variable.. But I can't get it working...
为什么这不起作用?
不用阅读你的代码,只阅读你的场景,我会使用 localStorage
来解决.这是一个例子,我将使用 prompt()
简称.
Without reading your code but just your scenario, I would solve by using localStorage
.
Here's an example, I'll use prompt()
for short.
在第 1 页:
window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}
在第 2 页:
window.onload = alert(localStorage.getItem("storageName"));
您也可以使用 cookie,但 localStorage 允许更多空间,并且在您请求页面时它们不会发送回服务器.
You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.