Getting the url parameters inside the html page

后端 未结 4 949
旧时难觅i
旧时难觅i 2020-12-30 07:16

I have a html page which is loaded using a url that looks a little like this:

http://localhost:8080/GisProject/MainService?s=C&o=1

I wo

相关标签:
4条回答
  • 2020-12-30 07:22

    A nice solution is given here:

    function GetURLParameter(sParam)
    {
        var sPageURL = window.location.search.substring(1);
        var sURLVariables = sPageURL.split('&');
        for (var i = 0; i < sURLVariables.length; i++) 
        {
            var sParameterName = sURLVariables[i].split('=');
            if (sParameterName[0] == sParam) 
            {
                return 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-12-30 07:34

    Assuming that our URL is https://example.com/?product=shirt&color=blue&newuser&size=m, we can grab the query string using window.location.search:

     const queryString = window.location.search;
     console.log(queryString);
     // ?product=shirt&color=blue&newuser&size=m
    

    We can then parse the query string’s parameters using URLSearchParams:

     const urlParams = new URLSearchParams(queryString);
    

    Then we call any of its methods on the result.

    For example, URLSearchParams.get() will return the first value associated with the given search parameter:

     const product = urlParams.get('product')
     console.log(product);
     // shirt
    
     const color = urlParams.get('color')
     console.log(color);
     // blue
    
     const newUser = urlParams.get('newuser')
     console log(newUser);
     // empty string
    

    Other Useful Methods

    0 讨论(0)
  • 2020-12-30 07:35

    Let's get a non-encoded URL for example:

    https://stackoverflow.com/users/3233722/pyk?myfirstname=sergio&mylastname=pyk

    Packing the job in a single JS line...

    urlp=[];s=location.toString().split('?');s=s[1].split('&');for(i=0;i<s.length;i++){u=s[i].split('=');urlp[u[0]]=u[1];}
    

    And just use it anywhere in your page :-)

    alert(urlp['mylastname']) //pyk
    
    • Even works on old browsers like ie6
    0 讨论(0)
  • 2020-12-30 07:38

    //http://localhost:8080/GisProject/MainService?s=C&o=1
    const params = new URLSearchParams(document.location.search);
    const s = params.get("s");
    const o = params.get("o");
    console.info(s); //show C
    console.info(o); //show 1

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