JavaScript get URL parameter data

Claim:

There are two pages: index.htmland login.html. login.htmlClick on the page to 登录jump to index.htmland pass the entered user name to index.html.

Realization effect:

Open the login.htmlpage:


Enter your user name:


Click to Login:

Realization ideas:

  1. The first login page, there is a submission form, actionsubmitted to the index.htmlpage

  2. The second page uses the parameters URLinside location.searchand uses the parameters of the first page to realize the data transfer effect between different pages

  3. In the second page, extract the parameters
    Insert picture description here

  4. Use substr, remove?

  5. Use split('=')split keys and values ​​to form an array of length 2

  6. The first element in the array is the key and the second element is the value. Take the value out

Code:

login.htmlpage:

<!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>
    <form action="index.html">
        用户名: <input type="text" name="uname">
        <input type="submit" value="登录">
    </form>
</body>

</html>

index.htmlpage:

<!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>
    <div></div>
    <script>
        // 1.先去掉?  substr('起始的位置',截取几个字符);
        var params = location.search.substr(1); // uname=andy

        // 2. 利用=把字符串分割为数组 split('=');
        var arr = params.split('=');

        var div = document.querySelector('div');
        // 3.把数据写入div中
        div.innerHTML = arr[1] + ':欢迎您';
    </script>
</body>

</html>

Guess you like

Origin blog.csdn.net/Jack_lzx/article/details/109270754