Domanda

    

Questa domanda ha già una risposta qui:

         

Se mi trovo su una pagina come

http://somesite.com/somepage.php?param1=asdf

Nel JavaScript di quella pagina, vorrei impostare una variabile sul valore del parametro nella parte GET dell'URL.

Quindi in JavaScript:

<script>
   param1var = ...   // ... would be replaced with the code to get asdf from URI
</script>

Cosa sarebbe " ... " essere?

È stato utile?

Soluzione

Ecco alcuni codice campione per quello.

<script>
var param1var = getQueryVariable("param1");

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
  alert('Query Variable ' + variable + ' not found');
}
</script>

Altri suggerimenti

Puoi ottenere " cerca " parte dell'oggetto location - e poi analizzalo.

var matches = /param1=([^&#=]*)/.exec(window.location.search);
var param1 = matches[1];

Ho fatto questa variante della soluzione di gnarf, quindi la chiamata e il risultato sono simili a PHP:

function S_GET(id){
    var a = new RegExp(id+"=([^&#=]*)");
    return decodeURIComponent(a.exec(window.location.search)[1]);
}

Ma come essere chiamato in una funzione rallenta il processo, è meglio usarlo come globale:

window['var_name '] = decodeURIComponent (/ var_in_get = ([^ & amp ; # =] *) /. exec (window.location.search) [1]);

Aggiorna

Mentre sto ancora imparando JS, ho creato una risposta migliore in un comportamento più JS:

Url = {
    get get(){
        var vars= {};
        if(window.location.search.length!==0)
            window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){
                key=decodeURIComponent(key);
                if(typeof vars[key]==="undefined") {vars[key]= decodeURIComponent(value);}
                else {vars[key]= [].concat(vars[key], decodeURIComponent(value));}
            });
        return vars;
    }
};

Questo permette di essere chiamato semplicemente usando Url.get .

Esempio L'URL ? Param1 = param1Value & amp; param2 = param2Value può essere chiamato come:

Url.get.param1 //"param1Value"
Url.get.param2 //"param2Value"

ecco uno snipet:

// URL GET params
url = "?a=2&a=3&b=2&a=4";

Url = {
    get get(){
        var vars= {};
        if(url.length!==0)
            url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){
                key=decodeURIComponent(key);
                if(typeof vars[key]==="undefined") {vars[key]= decodeURIComponent(value);}
                else {vars[key]= [].concat(vars[key], decodeURIComponent(value));}
            });
        return vars;
    }
};

document.querySelector('log').innerHTML = JSON.stringify(Url.get);
<log></log>

Dal mio archivio di programmazione:

function querystring(key) {
   var re=new RegExp('(?:\\?|&)'+key+'=(.*?)(?=&|$)','gi');
   var r=[], m;
   while ((m=re.exec(document.location.search)) != null) r[r.length]=m[1];
   return r;
}

Se il valore non esiste, viene restituito un array vuoto.
Se il valore esiste, viene restituito un array con un elemento, il valore.
Se esistono più valori con il nome, viene restituita una matrice contenente ciascun valore.

Esempi:

var param1var = querystring("param1")[0];

document.write(querystring("name"));

if (querystring('id')=='42') alert('We apoligize for the inconvenience.');

if (querystring('button').length>0) alert(querystring('info'));

Ecco come puoi farlo in Coffee Script (solo se qualcuno è interessato).

decodeURIComponent( v.split( "=" )[1] ) if decodeURIComponent( v.split( "=" )[0] ) == name for v in window.location.search.substring( 1 ).split( "&" )

Usi jquery? L'ho già usato prima: http://projects.allmarkedup.com/jquery_url_parser/ e questo ha funzionato abbastanza bene.

Sembrava ok:

function gup( name ){
   name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
   var regexS = "[\\?&]"+name+"=([^&#]*)";
   var regex = new RegExp( regexS );
   var results = regex.exec( window.location.href );
   if( results == null )
      return "";
   else
      return results[1];
}

Da http://www.netlobo.com/url_query_string_javascript.html

Ecco una versione che piace a JSLint:

/*jslint browser: true */
var GET = {};
(function (input) {
    'use strict';
    if (input.length > 1) {
        var param = input.slice(1).replace(/\+/g, ' ').split('&'),
            plength = param.length,
            tmp,
            p;

        for (p = 0; p < plength; p += 1) {
            tmp = param[p].split('=');
            GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp[1]);
        }
    }
}(window.location.search));

window.alert(JSON.stringify(GET));

O se hai bisogno di supporto per diversi valori per una chiave come ad es. ? key = value1 & amp; key = value2 puoi usare questo:

/*jslint browser: true */
var GET = {};
(function (input) {
    'use strict';
    if (input.length > 1) {
        var params = input.slice(1).replace(/\+/g, ' ').split('&'),
            plength = params.length,
            tmp,
            key,
            val,
            obj,
            p;

        for (p = 0; p < plength; p += 1) {
            tmp = params[p].split('=');
            key = decodeURIComponent(tmp[0]);
            val = decodeURIComponent(tmp[1]);
            if (GET.hasOwnProperty(key)) {
                obj = GET[key];
                if (obj.constructor === Array) {
                    obj.push(val);
                } else {
                    GET[key] = [obj, val];
                }
            } else {
                GET[key] = val;
            }
        }
    }
}(window.location.search));

window.alert(JSON.stringify(GET));

Puoi usare questa funzione

function getParmFromUrl(url, parm) {
    var re = new RegExp(".*[?&]" + parm + "=([^&]+)(&|$)");
    var match = url.match(re);
    return(match ? match[1] : "");
}

Se stai già eseguendo una pagina php, allora

bit php:

    $json   =   json_encode(

Se stai già eseguendo una pagina php, allora

bit php:

    var param1var = getVars.param1var;

js bit:

<*>

Ma per le pagine HTML, la soluzione di Jose Basilio mi sembra buona.

Buona fortuna!

REQUEST, JSON_FORCE_OBJECT); print "<script>var getVars = $json;</script>";

js bit:

<*>

Ma per le pagine HTML, la soluzione di Jose Basilio mi sembra buona.

Buona fortuna!

In realtà non devi fare nulla di speciale. Puoi mescolare JavaScript e PHP insieme per ottenere variabili da PHP direttamente in JavaScript.

var param1val = '<?php echo 

In realtà non devi fare nulla di speciale. Puoi mescolare JavaScript e PHP insieme per ottenere variabili da PHP direttamente in JavaScript.

<*>GET['param1'] ?>';
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top