Get escaped URL parameter

Szukam wtyczki jQuery, która może uzyskać parametry URL i obsługiwać ten ciąg wyszukiwania bez wyprowadzania błędu JavaScript: "nieprawidłowa Sekwencja URI". Jeśli nie ma jQuery plugin, który obsługuje to, muszę wiedzieć, jak zmodyfikować go do obsługi tego.

?search=%E6%F8%E5

Wartość parametru URL podczas dekodowania powinna wynosić:

æøå

(znaki są norweskie).

Nie mam dostępu do serwera, więc nie mogę nic na nim modyfikować.
Author: Sindre Sorhus, 2009-09-10

19 answers

function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}
 418
Author: James,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-27 06:02:01

Poniżej jest to, co stworzyłem z komentarzy tutaj, a także naprawianie błędów nie wymienionych (takich jak rzeczywiście zwracanie null, a nie 'null'):

function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
 293
Author: radicand,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-10 15:09:01

To, czego naprawdę chcesz, to jQuery Url Parser plugin. Dzięki tej wtyczce pobieranie wartości określonego parametru URL (dla bieżącego adresu URL) wygląda tak:

$.url().param('foo');

Jeśli chcesz obiekt z nazwami parametrów jako kluczami i wartościami parametrów jako wartościami, po prostu wywołaj param() bez argumentu, tak:

$.url().param();

Ta biblioteka działa również z innymi adresami URL, nie tylko bieżącym:

$.url('http://allmarkedup.com?sky=blue&grass=green').param();
$('#myElement').url().param(); // works with elements that have 'src', 'href' or 'action' attributes

Ponieważ jest to cała biblioteka parsowania adresów URL, możesz również uzyskać inne informacje z adresu URL, takie jak podany port, lub ścieżka, protokół itp.:

var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value');
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'

Ma również inne funkcje, sprawdź jego Strona główna aby uzyskać więcej dokumentów i przykładów.

Zamiast pisać własny parser URI do tego konkretnego celu, który tak jakby Działa w większości przypadków, użyj rzeczywistego parsera URI. W zależności od odpowiedzi kod z innych odpowiedzi może zwracać 'null' zamiast null, nie działa z pustymi parametrami (?foo=&bar=x), nie może parsować i zwraca wszystkie parametry na raz, powtarza pracę, jeśli wielokrotnie zapytujesz adres URL o parametry itp.

Użyj rzeczywistego parsera URI, nie wymyślaj własnego.

Dla tych, którzy nie lubią jQuery, jest wersja wtyczki, która jest czystym JS .

 106
Author: Lucas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-09 01:46:21

Jeśli nie wiesz, jakie będą parametry adresu URL i chcesz uzyskać obiekt z kluczami i wartościami, które są w parametrach, możesz użyć tego:

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;
}

Wywołanie getParameters () z adresem URL jak /posts?date=9/10/11&author=nilbus zwróci:

{
  date:   '9/10/11',
  author: 'nilbus'
}

Nie będę tu umieszczał kodu, ponieważ jest jeszcze dalej od pytania, ale weareon.net opublikowano bibliotekę, która pozwala na manipulację parametrami w adresie URL:

 43
Author: Edward Anderson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-21 18:19:09

Możesz użyć natywnej lokalizacji przeglądarki .search property:

function getParameter(paramName) {
  var searchString = window.location.search.substring(1),
      i, val, params = searchString.split("&");

  for (i=0;i<params.length;i++) {
    val = params[i].split("=");
    if (val[0] == paramName) {
      return unescape(val[1]);
    }
  }
  return null;
}

Ale są pewne wtyczki jQuery, które mogą Ci pomóc:

 40
Author: CMS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-09-10 07:56:55

Na podstawie odpowiedzi 999 :

function getURLParameter(name) {
    return decodeURIComponent(
        (location.search.match(RegExp("[?|&]"+name+'=(.+?)(&|$)'))||[,null])[1]
    );  
}

Zmiany:

  • decodeURI() zastępuje się decodeURIComponent()
  • [?|&] jest dodawane na początku wyrażenia regularnego
 26
Author: Eugene Yarmash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:45:31

Trzeba dodać parametr i, aby wielkość liter była niewrażliwa:

  function getURLParameter(name) {
    return decodeURIComponent(
      (RegExp(name + '=' + '(.+?)(&|$)', 'i').exec(location.search) || [, ""])[1]
    );
  }
 6
Author: Scott Wojan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-18 14:48:31
$.urlParam = function(name){
  var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(top.window.location.href); 
  return (results !== null) ? results[1] : 0;
}

$.urlParam("key");
 2
Author: Yoshi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-10 07:21:03

Na przykład funkcja, która zwraca wartość dowolnej zmiennej parametr.

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];
        }
    }
}​

I tak możesz użyć tej funkcji zakładając, że adres URL to,

"http://example.com/?technology=jquery&blog=jquerybyexample".

var tech = GetURLParameter('technology');
var blog = GetURLParameter('blog');

Więc w powyższym kodzie zmienna " tech "będzie miała wartość" jQuery", a zmienna" blog "będzie"jquerybyexample".

 2
Author: Rubyist,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-22 08:55:42

Nie powinieneś używać jQuery do czegoś takiego!
Nowoczesnym sposobem jest korzystanie z małych modułów wielokrotnego użytku za pośrednictwem menedżera pakietów, takiego jak Bower.

Stworzyłem małymoduł , który może przetworzyć łańcuch zapytania do obiektu. Użyj go tak:

// parse the query string into an object and get the property
queryString.parse(unescape(location.search)).search;
//=> æøå
 2
Author: Sindre Sorhus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-15 02:29:13

Po przeczytaniu wszystkich odpowiedzi skończyłem z tą wersją z + drugą funkcją używającą parametrów jako Flag

function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)','i').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}

function isSetURLParameter(name) {
    return (new RegExp('[?|&]' + name + '(?:[=|&|#|;|]|$)','i').exec(location.search) !== null)
}
 1
Author: Neon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-06 18:22:07

Jest tu dużo błędnego kodu, a rozwiązania regex są bardzo powolne. Znalazłem rozwiązanie, które działa do 20x szybciej niż odpowiednik regex i jest elegancko proste:

    /*
    *   @param      string      parameter to return the value of.
    *   @return     string      value of chosen parameter, if found.
    */
    function get_param(return_this)
    {
        return_this = return_this.replace(/\?/ig, "").replace(/=/ig, ""); // Globally replace illegal chars.

        var url = window.location.href;                                   // Get the URL.
        var parameters = url.substring(url.indexOf("?") + 1).split("&");  // Split by "param=value".
        var params = [];                                                  // Array to store individual values.

        for(var i = 0; i < parameters.length; i++)
            if(parameters[i].search(return_this + "=") != -1)
                return parameters[i].substring(parameters[i].indexOf("=") + 1).split("+");

        return "Parameter not found";
    }

console.log(get_param("parameterName"));

Regex nie jest rozwiązaniem be-all I end-all, dla tego typu problemu prosta manipulacja ciągiem może działać znacznie wydajniej. Źródło kodu .

 0
Author: George Anthony,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-02 01:04:15
<script type="text/javascript">
function getURLParameter(name) {
        return decodeURIComponent(
            (location.search.toLowerCase().match(RegExp("[?|&]" + name + '=(.+?)(&|$)')) || [, null])[1]
        );
    }

</script>

getURLParameter(id) lub getURLParameter(Id) działa tak samo:)

 0
Author: user2310887,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-06 09:31:22

Fragment kodu JQuery, aby uzyskać dynamiczne zmienne zapisane w adresie url jako parametry i zapisać je jako zmienne JavaScript gotowe do użycia ze skryptami:

$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results==null){
       return null;
    }
    else{
       return results[1] || 0;
    }
}

example.com?param1=name&param2=&id=6

$.urlParam('param1'); // name
$.urlParam('id');        // 6
$.urlParam('param2');   // null

//example params with spaces
http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));  
//output: Gold%20Coast

console.log(decodeURIComponent($.urlParam('city'))); 
//output: Gold Coast
 0
Author: Reza Baradaran Gazorisangi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-18 08:48:52
function getURLParameters(paramName) 
{
        var sURL = window.document.URL.toString();  
    if (sURL.indexOf("?") > 0)
    {
       var arrParams = sURL.split("?");         
       var arrURLParams = arrParams[1].split("&");      
       var arrParamNames = new Array(arrURLParams.length);
       var arrParamValues = new Array(arrURLParams.length);     
       var i = 0;
       for (i=0;i<arrURLParams.length;i++)
       {
        var sParam =  arrURLParams[i].split("=");
        arrParamNames[i] = sParam[0];
        if (sParam[1] != "")
            arrParamValues[i] = unescape(sParam[1]);
        else
            arrParamValues[i] = "No Value";
       }

       for (i=0;i<arrURLParams.length;i++)
       {
                if(arrParamNames[i] == paramName){
            //alert("Param:"+arrParamValues[i]);
                return arrParamValues[i];
             }
       }
       return "No Parameters Found";
    }

}
 -1
Author: Dhiral Pandya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-05 20:21:19

Stworzyłem prostą funkcję do pobierania parametru URL w JavaScript z takiego adresu URL:

.....58e/web/viewer.html?page=*17*&getinfo=33


function buildLinkb(param) {
    var val = document.URL;
    var url = val.substr(val.indexOf(param))  
    var n=parseInt(url.replace(param+"=",""));
    alert(n+1); 
}
buildLinkb("page");

Wyjście: 18

 -1
Author: Code Spy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-24 16:16:59

Na wszelki wypadek, gdybyście mieli adres URL, taki jak localhost / index.xsp?a = 1 # coś i trzeba dostać param a nie hash.

var vars = [], hash, anchor;
var q = document.URL.split('?')[1];
if(q != undefined){
    q = q.split('&');
    for(var i = 0; i < q.length; i++){
        hash = q[i].split('=');
        anchor = hash[1].split('#');
        vars.push(anchor[0]);
        vars[hash[0]] = anchor[0];
    }
}
 -1
Author: Ancyent,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-25 08:45:05

Mała modyfikacja odpowiedzi przez @ pauloppenheim, ponieważ nie będzie poprawnie obsługiwać nazw parametrów, które mogą być częścią innych nazw parametrów.

Np: jeśli masz parametry "appenv" & "env", ponowne nadanie wartości " env "może podnieść wartość" appenv".

Fix:

var urlParamVal = function (name) {
    var result = RegExp("(&|\\?)" + name + "=(.+?)(&|$)").exec(location.search);
    return result ? decodeURIComponent(result[2]) : "";
};
 -1
Author: lasantha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-30 21:29:16

To może pomóc.

<script type="text/javascript">
    $(document).ready(function(){
        alert(getParameterByName("third"));
    });
    function getParameterByName(name){
        var url     = document.URL,
            count   = url.indexOf(name);
            sub     = url.substring(count);
            amper   = sub.indexOf("&"); 

        if(amper == "-1"){
            var param = sub.split("=");
            return param[1];
        }else{
            var param = sub.substr(0,amper).split("=");
            return param[1];
        }

    }
</script>
 -2
Author: Ram Guiao,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-13 01:34:12