AngularJS:获取链接中没有哈希的查询字符串值

Far*_*san 13 javascript php angularjs

我试图使用angularjs获取查询字符串值.

我的网址: http://localhost/example.php?sportsId=3

我应用var goto = $location.search()['sportsId']; 它时返回undefined.

但是,如果我在url中添加hash就像 Url: http://localhost/example.php#?sportsId=3

然后它返回正确的值3.

但在这种情况下,它也给了我 Error: [$parse:syntax] http://errors.angularjs.org/1.3.8/$parse/syntax?p0=undefined&p1=not%20a%20primary%20expression&p2=null&p3=sportsID%3D&p4=sportsID%3D

此外,我的默认$_REQUEST['sportsId']值不适用于哈希格式.

如何使用angularjs从查询字符串中正确获取值?

pro*_*ype 27

我知道这不是Angular,而是纯粹的JS,就像一个魅力(只是不添加dummyPath,它将采用URL).

function getUrlParameter(param, dummyPath) {
        var sPageURL = dummyPath || window.location.search.substring(1),
            sURLVariables = sPageURL.split(/[&||?]/),
            res;

        for (var i = 0; i < sURLVariables.length; i += 1) {
            var paramName = sURLVariables[i],
                sParameterName = (paramName || '').split('=');

            if (sParameterName[0] === param) {
                res = sParameterName[1];
            }
        }

        return res;
}
Run Code Online (Sandbox Code Playgroud)

用法:

var sportdsId = getUrlParameter('sportsId');
Run Code Online (Sandbox Code Playgroud)

  • 尼斯.只需解码字符串:res = decodeURIComponent(sParameterName [1] .replace(/\+/g,"")); (3认同)