How to get URL parameter using jQuery or plain JavaScript?

前端 未结 30 3242
天涯浪人
天涯浪人 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:03

    I hope this will help.

     <script type="text/javascript">
       function getParameters() {
         var searchString = window.location.search.substring(1),
           params = searchString.split("&"),
           hash = {};
    
         if (searchString == "") return {};
         for (var i = 0; i < params.length; i++) {
           var val = params[i].split("=");
           hash[unescape(val[0])] = unescape(val[1]);
         }
    
         return hash;
       }
    
        $(window).load(function() {
          var param = getParameters();
          if (typeof param.sent !== "undefined") {
            // Do something.
          }
        });
    </script>
    
    0 讨论(0)
  • 2020-11-21 07:03

    I use this and it works. http://codesheet.org/codesheet/NF246Tzs

    function getUrlVars() {
        var vars = {};
        var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
        });
    return vars;
    }
    
    
    var first = getUrlVars()["id"];
    
    0 讨论(0)
  • 2020-11-21 07:05

    Or you can use this neat little function, because why overcomplicated solutions?

    function getQueryParam(param, defaultValue = undefined) {
        location.search.substr(1)
            .split("&")
            .some(function(item) { // returns first occurence and stops
                return item.split("=")[0] == param && (defaultValue = item.split("=")[1], true)
            })
        return defaultValue
    }
    

    which looks even better when simplified and onelined:

    tl;dr one-line solution

    var queryDict = {};
    location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
    
    result:
    queryDict['sent'] // undefined or 'value'
    

    But what if you have got encoded characters or multivalued keys?

    You better see this answer: How can I get query string values in JavaScript?

    Sneak peak

    "?a=1&b=2&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab"
    > queryDict
    a: ["1", "5", "t e x t"]
    b: ["2"]
    c: ["3"]
    d: [undefined]
    e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]
    
    > queryDict["a"][1] // "5"
    > queryDict.a[1] // "5"
    
    0 讨论(0)
  • 2020-11-21 07:07

    Yet another alternative function...

    function param(name) {
        return (location.search.split(name + '=')[1] || '').split('&')[0];
    }
    
    0 讨论(0)
  • 2020-11-21 07:08

    Best solution here.

    var getUrlParameter = function getUrlParameter(sParam) {
        var sPageURL = window.location.search.substring(1),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i;
    
        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');
    
            if (sParameterName[0] === sParam) {
                return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
            }
        }
    };
    

    And this is how you can use this function assuming the URL is,
    http://dummy.com/?technology=jquery&blog=jquerybyexample.

    var tech = getUrlParameter('technology');
    var blog = getUrlParameter('blog');
    
    0 讨论(0)
  • 2020-11-21 07:08

    function GetRequestParam(param)
    {
    	var res = null;
    	try{
    		var qs = decodeURIComponent(window.location.search.substring(1));//get everything after then '?' in URI
    		var ar = qs.split('&');
    		$.each(ar, function(a, b){
    			var kv = b.split('=');
    			if(param === kv[0]){
    				res = kv[1];
    				return false;//break loop
    			}
    		});
    	}catch(e){}
    	return res;
    }

    0 讨论(0)
提交回复
热议问题