How to get “GET” request parameters in JavaScript?

2019-01-01 05:36发布

How to get "GET" variables from request in JavaScript?

Does jQuery or YUI! have this feature built-in?

标签: javascript
11条回答
长期被迫恋爱
2楼-- · 2019-01-01 06:12

A map-reduce solution:

var urlParams = location.search.split(/[?&]/).slice(1).map(function(paramPair) {
        return paramPair.split(/=(.+)?/).slice(0, 2);
    }).reduce(function (obj, pairArray) {            
        obj[pairArray[0]] = pairArray[1];
        return obj;
    }, {});

Usage:

For url: http://example.com?one=1&two=2
console.log(urlParams.one) // 1
console.log(urlParams.two) // 2
查看更多
萌妹纸的霸气范
3楼-- · 2019-01-01 06:13

If you already use jquery there is a jquery plugin that handles this:

http://plugins.jquery.com/project/query-object

查看更多
步步皆殇っ
4楼-- · 2019-01-01 06:15

You can parse the URL of the current page to obtain the GET parameters. The URL can be found by using location.href.

查看更多
笑指拈花
5楼-- · 2019-01-01 06:17

All data is available under

window.location.search

you have to parse the string, eg.

function get(name){
   if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
      return decodeURIComponent(name[1]);
}

just call the function with GET variable name as parameter, eg.

get('foo');

this function will return the variables value or undefined if variable has no value or doesn't exist

查看更多
ら面具成の殇う
6楼-- · 2019-01-01 06:17

try the below code, it will help you get the GET parameters from url . for more details.

 var url_string = window.location.href; // www.test.com?filename=test
    var url = new URL(url_string);
    var paramValue = url.searchParams.get("filename");
    alert(paramValue)
查看更多
登录 后发表回答