How to get URL parameter using jQuery or plain JavaScript?

前端 未结 30 3211
天涯浪人
天涯浪人 2020-11-21 06:29

I have seen lots of jQuery examples where parameter size and name are unknown.

My URL is only going to ever have 1 string:

http://example.com?sent=ye         


        
30条回答
  •  情歌与酒
    2020-11-21 07:17

    Another solution that uses jQuery and JSON, so you can access the parameter values through an object.

    var loc = window.location.href;
    var param = {};
    if(loc.indexOf('?') > -1)
    {
        var params = loc.substr(loc.indexOf('?')+1, loc.length).split("&");
    
        var stringJson = "{";
        for(var i=0;i

    Assuming your URL is http://example.com/?search=hello+world&language=en&page=3

    After that it's only a matter of using the parameters like this:

    param.language
    

    to return

    en
    

    The most useful usage of this is to run it at page load and make use of a global variable to use the parameters anywhere you might need them.

    If your parameter contains numeric values then just parse the value.

    parseInt(param.page)
    

    If there are no parameters param will just be an empty object.

提交回复
热议问题