简体   繁体   English

从Javascript中的URL获取参数

[英]GET parameters from URL in Javascript

newbie here. 新手在这里。 I've made a simple form in the index.html as you can see below: 我在index.html中做了一个简单的表格,如下所示:

<form name="parameters" METHOD="GET" ACTION="pag1.html">
login: <INPUT TYPE="text" NAME="login"> 
password: <INPUT TYPE="text" NAME="password"> 
<input type="submit" value="ok">
</form>

On pag1.html i've placed my javascript to split the URL, as you can see below: 在pag1.html上,我放置了JavaScript来拆分URL,如下所示:

<head>
<script language="JavaScript">
function processUser()
  {
    var parameters = location.search.substring(1).split("&");

var temp = parameters[0].split("=");
l = unescape(temp[1]);
temp = parameters[1].split("=");
p = unescape(temp[1]);
document.getElementById("log").innerHTML = l;
document.getElementById("pass").innerHTML = p;
  }
</script>
</head>

And two DIVs to display both of them: 和两个DIV来显示它们两个:

<div id="log">LOGIN:</div>
<div id="pass">PASSWORD:</div>

The URL on pag1.html is like: " pag1.html?login=123&password=asd " pag1.html上的URL类似于:“ pag1.html?login = 123&password = asd”

But all that i get is : 但是我得到的是:
LOGIN: 登录:
PASSWORD: 密码:

Where did i go wrong? 我哪里做错了?

It's just because your code is executed before #log and #pass rendering in the DOM. 这仅仅是因为您的代码是在DOM中的#log和#pass渲染之前执行的。 Just put your before the closing tag and it will works. 只需将您的标签放在结束标记之前,它将起作用。

Your function should be called after whole HTML is loaded. 加载整个HTML之后,应调用您的函数。 To do that you need to place your function as a callback of DOMContentLoaded event. 为此,您需要将函数放置为DOMContentLoaded事件的回调。

document.addEventListener("DOMContentLoaded", function(){
    function processUser()
    {
         var parameters = location.search.substring(1).split("&");

         var temp = parameters[0].split("=");
         l = unescape(temp[1]);
         temp = parameters[1].split("=");
         p = unescape(temp[1]);
         document.getElementById("log").innerHTML = l;
         document.getElementById("pass").innerHTML = p;
    }

    processUser();
})

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM