Using the GET parameter of a URL in JavaScript [du

2019-01-01 13:30发布

This question already has an answer here:

If I am on a page such as

http://somesite.com/somepage.php?param1=asdf

In the JavaScript of that page, I would like to set a variable to the value of the parameter in the GET part of the URL.

So in JavaScript:

<script>
   param1var = ...   // ... would be replaced with the code to get asdf from URI
</script>

What would "..." be?

11条回答
孤独总比滥情好
2楼-- · 2019-01-01 14:04

From my programming archive:

function querystring(key) {
   var re=new RegExp('(?:\\?|&)'+key+'=(.*?)(?=&|$)','gi');
   var r=[], m;
   while ((m=re.exec(document.location.search)) != null) r[r.length]=m[1];
   return r;
}

If the value doesn't exist, an empty array is returned.
If the value exists, an array is return that has one item, the value.
If several values with the name exists, an array containing each value is returned.

Examples:

var param1var = querystring("param1")[0];

document.write(querystring("name"));

if (querystring('id')=='42') alert('We apoligize for the inconvenience.');

if (querystring('button').length>0) alert(querystring('info'));
查看更多
低头抚发
3楼-- · 2019-01-01 14:05

You can use this function

function getParmFromUrl(url, parm) {
    var re = new RegExp(".*[?&]" + parm + "=([^&]+)(&|$)");
    var match = url.match(re);
    return(match ? match[1] : "");
}
查看更多
其实,你不懂
4楼-- · 2019-01-01 14:06

You can get the "search" part of the location object - and then parse it out.

var matches = /param1=([^&#=]*)/.exec(window.location.search);
var param1 = matches[1];
查看更多
美炸的是我
5楼-- · 2019-01-01 14:08

If you're already running a php page then

php bit:

    $json   =   json_encode($_REQUEST, JSON_FORCE_OBJECT);
    print "<script>var getVars = $json;</script>";

js bit:

    var param1var = getVars.param1var;

But for Html pages Jose Basilio's solution looks good to me.

Good luck!

查看更多
怪性笑人.
6楼-- · 2019-01-01 14:14

Here's how you could do it in Coffee Script (just if anyone is interested).

decodeURIComponent( v.split( "=" )[1] ) if decodeURIComponent( v.split( "=" )[0] ) == name for v in window.location.search.substring( 1 ).split( "&" )
查看更多
登录 后发表回答