从QueryString和Hash中读取值

Reading values both from QueryString and Hash?

本文关键字:读取 Hash QueryString      更新时间:2023-09-26

有很多js代码来读取查询字符串。

然而,在我看到facebook login的回复后,这是类似

的东西

http://localhost:55643/WebSite2/HTMLPage2.htm#access_token=CAACSIC6Koe......roHXCK8ZD&expires_in=5439

我对自己说,我必须写一些代码来处理哈希(#)之后的值。

于是我照做了:

(function ($)
    {
        $.getQs = function (specificUrl)
        {
            var st = specificUrl || window.location.href;
            var o = {}, e;
            var re = /([^#?&=]+)=([^&#]*)/ig;
            while (e = re.exec(st))
            {
                o[e[1]] = e[2];
            }
            //console.log(o);
            return o;
        }
    })(jQuery);

这将返回 对象 QShash

下的所有值

(如果没有定义specifiedUrl -它将查看浏览器的url)

用法1 : (特定 URL):

console.log($.getQs('www.example.com?ferko=suska&ee=huu#a=1&b=2&c=3'));

这将返回

Object {ferko: "suska", ee: "huu", a: "1", b: "2", c: "3"}

用法2: (当前 URL):

我当前的URL:

http://localhost:55643/WebSite2/HTMLPage.htm?ferko=suska&ee=huu#a=1&b=2&c=3

so $.getQs()

也收益率

Object {ferko: "suska", ee: "huu", a: "1", b: "2", c: "3"}

那么问题在哪里呢?

在这里:

http://localhost:55643/WebSite2/HTMLPage.htm?ferko=suska&ee=huu#a=1&b=2&c=3&ee=grrr

注意QS侧有ee, hash侧也有ee

我如何在我的对象中反映它?

<标题>编辑

这就是我如何读取facebook的期望值

console.log($.getQs('http://localhost:55643/WebSite2/HTMLPage2.htm#access_token=CAACSIC6KoeroHXCK8ZD&expires_in=5439').access_token);

收益率

CAACSIC6KoeroHXCK8ZD

(function ($) {
    $.getQs = function (specificUrl) {
        function parseToObj(str, re) {
          var o = {};
          while(e = re.exec(str))
            o[e[1]] = e[2];
          return o;
        }
        var st = specificUrl || window.location.href;
        return {
          beforeHash: parseToObj(st, /([^#?&=]+)=([^&#]*)(?=.*?'#)/ig),
          afterHash: parseToObj(st, /([^#?&=]+)=([^&#]*)(?!.*?'#)/ig)
        };
    }
})(jQuery);

或更好的解决方案:

(function ($) {
    $.getQs = function (specificUrl) {
        function parseToObj(str, re) {
          var o = {};
          while(e = re.exec(str))
            o[e[1]] = e[2];
          return o;
        }
        var st = specificUrl || window.location.href;
        var hashPos = st.indexOf('#');
        if(hashPos == -1) hashPos = st.length;
        return {
          beforeHash: parseToObj(st.substring(0, hashPos), /([^#?&=]+)=([^&#]*)/ig),
          afterHash: parseToObj(st.substring(hashPos), /([^#?&=]+)=([^&#]*)/ig)
        };
    }
})(jQuery);