gpt4 book ai didi

javascript - 使用单个 JavaScript 源文件将数据从表单传递到多个网页

转载 作者:行者123 更新时间:2023-11-30 13:57:47 24 4
gpt4 key购买 nike

我用硬编码的用户名和密码创建了一个简单的登录页面,一旦登录凭据通过,我就成功调用了下一个页面,但是我很难将在第 1 页输入的用户名传递到第 2 页.

我试图找到一种方法将用户输入作为 js 文件中的全局变量,以便我可以在第二页中使用相同的变量,但我没有成功。

greeter.html

<body>
<h1>Simple Login Page</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form);" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
<p id = "passwarn"></p>
<script language="javascript" src="source.js">

</script>
</body>

源代码.js

function check(form) { /*function to check userid & password*/
/*the following code checkes whether the entered userid and password are
matching*/
let uid = form.userid.value;
let pswrd = form.pswrd.value;
if(uid == "shiva" && pswrd == "mypswrd") {
window.open('test.html')/*opens the target page while Id & password
matches*/
}
else {
document.getElementById("passwarn").innerHTML = "User name or
password is incorrect!"/*displays error message*/
}
}

测试.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">

<title>Document</title>
</head>
<body>
<script language="javascript" src="source.js"></script>
<h1> Hello <span id = "UI"></span></h1>
</body>
</html>

我想在 test.html 页面上打印 Hello shiva,我不想在这样做时使用 jquery,有什么办法吗?

最佳答案

您可以简单地在 test.html 中引用起始页的值。

为了使事情更简单,将 ID 添加到用户名字段:

Username <input type="text" name="userid" id="userid">

然后你可以像这样从打开的窗口中抓取并显示值:

<h1> Hello 
<script>
document.write(window.opener.document.getElementById("userid").value)
</script>
</h1>

如果您想更优雅地做事,您可以将脚本保留在您的 .js 文件中,并从那里更改“UI”范围的 innerHTML。

请记住,跨源脚本规则意味着这仅在从同一域提供服务时才有效。

关于javascript - 使用单个 JavaScript 源文件将数据从表单传递到多个网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56886541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com