2012-03-26 10 views
44

devo URL simile a questo:Come ottenere la stringa di query dall'URL corrente con JavaScript?

http://localhost/PMApp/temp.htm?ProjectID=462 

Che cosa devo fare è quello di ottenere i dettagli dopo il ? segno (query string) - cioè ProjectID=462. Come posso ottenere che usando JavaScript?

Quello che ho fatto finora è questo:

var url = window.location.toString(); 
url.match(?); 

Io non so che cosa fare dopo.

+0

Scegli questa http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript – slash197

+0

@Cupcake: Tale questione è di circa i parametri di estrazione, in questa sede solo su come ottenere 'posizione. search' – Bergi

+0

Votazione per riaprire, il duplicato contrassegnato è una richiesta per una libreria, considerando che questa domanda riguarda l'ottenimento del codice js. – 1615903

risposta

93

Dai un'occhiata allo MDN article su window.location.

QueryString è disponibile in window.location.search.

Soluzione che funzionano nei browser legacy così

MDN fornire un esempio (non è più disponibile nel suddetto articolo fa riferimento) di come ottenere il valore di un singolo tasto disponibile nel QueryString. Qualcosa di simile a questo:

function getQueryStringValue (key) { 
    return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1")); 
} 

// Would write the value of the QueryString-variable called name to the console 
console.log(getQueryStringValue("name")); 

nei browser moderni

Nei browser moderni hanno la proprietà searchParams dell'interfaccia URL, che restituisce un oggetto URLSearchParams. L'oggetto restituito ha un numero di metodi convenienti, incluso un metodo get. Così l'equivalente del nell'esempio precedente sarebbe:

let params = (new URL(document.location)).searchParams; 
let name = params.get("name"); 

L'interfaccia URLSearchParams può essere utilizzato anche per analizzare le stringhe in un formato querystring, e li trasformano in un pratico URLSearchParams oggetto.

let paramsString = "name=foo&age=1337" 
let searchParams = new URLSearchParams(paramsString); 

searchParams.has("name") === true; // true 
searchParams.get("age") === "1337"; // true 

Si noti che il supporto del browser è ancora limitata su questa interfaccia, quindi se avete bisogno di supportare i browser legacy, bastone con il primo esempio.

+0

Solo un nota: usa sempre 'encodeURIComponent/decodeURIComponent' invece di' escape/unescape' – tsh

2

È possibile utilizzare la proprietàdell'oggetto window.location per ottenere la parte di query dell'URL. Si noti che include il punto interrogativo (?) All'inizio, nel caso in cui ciò influisce sul modo in cui si intende analizzarlo.

37

Usa window.location.search per ottenere tutto dopo ?compreso ?

Esempio:

var url = window.location.search; 
url = url.replace("?", ''); // remove the ? 
alert(url); //alerts ProjectID=462 is your case 
+4

O anche più semplice: 'lascia querystring = window.location.search.substring (1);' – olibre

6

Questo aggiungerà una funzione globale per accedere alle variabili querystring come una mappa.

// ------------------------------------------------------------------------------------- 
// Add function for 'window.location.query([queryString])' which returns an object 
// of querystring keys and their values. An optional string parameter can be used as 
// an alternative to 'window.location.search'. 
// ------------------------------------------------------------------------------------- 
// Add function for 'window.location.query.makeString(object, [addQuestionMark])' 
// which returns a queryString from an object. An optional boolean parameter can be 
// used to toggle a leading question mark. 
// ------------------------------------------------------------------------------------- 
if (!window.location.query) { 
    window.location.query = function (source) { 
     var map = {}; 
     source = source || this.search; 

     if ("" != source) { 
      var groups = source, i; 

      if (groups.indexOf("?") == 0) { 
       groups = groups.substr(1); 
      } 

      groups = groups.split("&"); 

      for (i in groups) { 
       source = groups[i].split("=", 
        // For: xxx=, Prevents: [xxx, ""], Forces: [xxx] 
        (groups[i].slice(-1) !== "=") + 1 
       ); 

       // Key 
       i = decodeURIComponent(source[0]); 

       // Value 
       source = source[1]; 
       source = typeof source === "undefined" 
        ? source 
        : decodeURIComponent(source); 

       // Save Duplicate Key 
       if (i in map) { 
        if (Object.prototype.toString.call(map[i]) !== "[object Array]") { 
         map[i] = [map[i]]; 
        } 

        map[i].push(source); 
       } 

       // Save New Key 
       else { 
        map[i] = source; 
       } 
      } 
     } 

     return map; 
    } 

    window.location.query.makeString = function (source, addQuestionMark) { 
     var str = "", i, ii, key; 

     if (typeof source == "boolean") { 
      addQuestionMark = source; 
      source = undefined; 
     } 

     if (source == undefined) { 
      str = window.location.search; 
     } 
     else { 
      for (i in source) { 
       key = "&" + encodeURIComponent(i); 

       if (Object.prototype.toString.call(source[i]) !== "[object Array]") { 
        str += key + addUndefindedValue(source[i]); 
       } 
       else { 
        for (ii = 0; ii < source[i].length; ii++) { 
         str += key + addUndefindedValue(source[i][ii]); 
        } 
       } 
      } 
     } 

     return (addQuestionMark === false ? "" : "?") + str.substr(1); 
    } 

    function addUndefindedValue(source) { 
     return typeof source === "undefined" 
      ? "" 
      : "=" + encodeURIComponent(source); 
    } 
} 

Divertiti.

3

È possibile utilizzare questa funzione per la stringa divisa?id =

function myfunction(myvar){ 
    var urls = myvar; 
    var myurls = urls.split("?id="); 
    var mylasturls = myurls[1]; 
    var mynexturls = mylasturls.split("&"); 
    var url = mynexturls[0]; 
    alert(url) 
} 
myfunction(window.top.location.href); 
myfunction("http://www.myname.com/index.html?id=dance&emp;cid=in_social_facebook-hhp-food-moonlight-influencer_s7_20160623"); 

qui è la fiddle

2
var queryObj = {}; 
    if(url.split("?").length>0){ 
    var queryString = url.split("?")[1]; 
    } 

ora avete la parte query in queryString

Prima sostituire rimuoverà tutti gli spazi bianchi, secondo sostituirà tutti i '&' parte con "" e, infine, la terza sostituzione metterà ": "al posto dei segni '='.

queryObj = JSON.parse('{"' + queryString.replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}') 

Quindi diciamo hai avuto una query come abc = 123 & EFG = 456. Ora prima dell'analisi, la tua query viene convertita in qualcosa come {"abc": "123", "efg": "456"}. Ora, quando lo analizzerete, vi fornirà la vostra richiesta in json object.

+0

Mentre questo codice può rispondere alla domanda, fornendo un contesto aggiuntivo riguardo il modo e/o il motivo per cui risolve il problema migliorerebbe il valore a lungo termine della risposta. – Badacadabra

+0

Modificata la risposta. Spero che andrà bene ora. –

2
window.location.href.slice(window.location.href.indexOf('?') + 1); 
Problemi correlati