查询地址栏字符串参数

  虽然大家都知道可以通过location.search可以访问URL的以问号开头的字符串,但是这样的字符串却没有办法逐个访问其中的每个查询字符串的参数。为此,我创建了以下的函数,用来解析查询字符串,然后返回一个包含所有参数的对象。

  一:输入信息的页面

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>输入信息页</title>
    </head>
    <body>
        <form action="ok.html" method="get">
            <input type="text" name="search">
            <input type="password" name="psd">
            <input type="submit">
        </form>
    </body>
</html>

  二:带有输入信息的查询页

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>提交成功</title>
    </head>
    <body>
        <h1>提交成功</h1>
        <script type="text/javascript">
            var getQueryStringArgs = function (){
                //此处以?search=555&psd=555444为例举例说明/*取得查询字符串并且去掉开头的问号,
                 * 如果有?之后有字符串,则qs = location.search.substring(1),否则为空字符串
                */
                var qs = (location.search.length > 0 ? location.search.substring(1) : ''),
                //声明一个空的对象用来保存数据
                    args = {},
                    //如果qs不是空字符串,则items = 一个类似["search=555", "psd=555444"]的数组,否则为[];
                    items = qs.length ? qs.split('&') : [],
                    item = null,
                    name = null,
                    value = null;
                for (var i = 0; i < items.length; i++) {
                    //item[0] = ["search", "555"]; item[1] = ["psd", "555444"];
                    item = items[i].split('=');
                    //name = search/psd
                    name = decodeURIComponent(item[0]);
                    /*
                     * value = 555/555444
                     * decodeURIComponent() 函数可对 encodeURIComponent() 函数编码的 URI 进行解码。
                     * var str = "http://www.w3school.com.cn/My first/";
                     * encodeURIComponent(str)
                     * decodeURIComponent(str)
                     */
                    value = decodeURIComponent(item[1]);
                    //把search/psd赋值给args的name,把555/555444赋值给args的value
                    if (name.length){
                        args[name] = value;
                    };
                }
                return args;
            }
            
            var result = getQueryStringArgs();
            console.log(result);
        </script>
    </body>
</html>

  以上代码解析:

  第一步:先去掉查询字符串开头的问号。当然,前提是location.search中必须要包含一个或者多个字符。

  第二步:所有的参数将会被保存在args对象中,该对象以字面量的形式创建。

  第三步:根据和号("&")来查询分割字符串,并返回name = value格式的字符串数组。下面的for循环会迭代这个数组,然后再根据"="号分割每一项数组,从而返回第一项为参数名,第二项为参数值的数组。在使用decodeURIComponent()分别解码name和value(因为查询字符串应该是被解码过的)。

  第四步:将name作为args对象的属性,将value作为相应属性的值。

  第五步:在需要的页面调用即可;

  ?

posted @ 2017-05-11 19:16  谭翔随笔  阅读(399)  评论(0编辑  收藏  举报