2012-03-08 10 views
13

Diciamo che ho un URL, ad esempio:aggiornamento con jQuery

http://www.example.com/hello.png?w=100&h=100&bg=white 

Quello che mi piacerebbe fare è aggiornare i valori della querystring w e h, ma lasciare il bg querystring intatto , per esempio:

http://www.example.com/hello.png?w=200&h=200&bg=white 

Allora, qual è il modo più efficiente più veloce per leggere i valori querystring (e potrebbero essere qualsiasi insieme di valori querystring, non solo w, h, e bg), aggiornare pochi o nessuno di i valori e restituire l'url completo con la nuova querystring?

Quindi:

  1. ottenere i valori di ogni tasto
  2. Aggiornamento querystring qualsiasi numero di tasti
  3. Ricostruire l'url con i nuovi valori
  4. Tenere tutti gli altri valori che weren' t aggiornato
  5. Non avrà un set standard di chiavi conosciute, potrebbe cambiare per URL

risposta

14

ottenere i valori di stringa di query questo way e utilizzare $.param per ricostruire query string

UPDATE:

Questo è un esempio, controllare anche fiddle:

function getQueryVariable(url, variable) { 
 
    \t var query = url.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]; 
 
      } 
 
    } 
 

 
    return false; 
 
    } 
 

 
    var url = 'http://www.example.com/hello.png?w=100&h=100&bg=white'; 
 
     
 
    var w = getQueryVariable(url, 'w'); 
 
    var h = getQueryVariable(url, 'h'); 
 
    var bg = getQueryVariable(url, 'bg'); 
 

 
    // http://www.example.com/hello.png?w=200&h=200&bg=white 
 
    var params = { 'w':200, 'h':200, 'bg':bg }; 
 
    var new_url = 'http://www.example.com/hello.png?' + jQuery.param(params);

È possibile modificare la funzione per utilizzare l'url corrente:

function getQueryVariable(variable) { 
 
    \t 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]; 
 
      } 
 
    } 
 

 
    return false; 
 
    }

+0

Questa risposta è stato contrassegnato per la rimozione come una risposta link-solo. Potresti aggiornare la risposta in modo che risolva la domanda senza richiedere al lettore di fare clic sui collegamenti? – josliber

+0

e se avessimo bisogno di aggiornare solo alcune delle variabili e abbiamo molte variabili in url che non stiamo per aggiornare? –

3

Un altro modo (indipendente di jQuery o di altre biblioteche): https://github.com/Mikhus/jsurl

var u = new Url; 
// or 
var u = new Url('/some/path?foo=baz'); 
alert(u); 
u.query.foo = 'bar'; 
alert(u); 
+0

Questa libreria è ora denominata [domurl] (https://github.com/Mikhus/domurl). GitHub sta reindirizzando al repository corretto, pubblicando solo qui nel caso in cui dovesse mai cambiare. – vaindil

0

mio URL è simile a questo: http://localhost/dentistryindia/admin/hospital/add_procedure?hid=241&hpr_id=12

var reExp = /hpr_id=\\d+/; 
var url = window.location.href; 
url = url.toString(); 
var hrpid = $("#category :selected").val(); //new value to replace hpr_id 
var reExp = new RegExp("[\\?&]" + 'hpr_id' + "=([^&#]*)"), 
delimeter = reExp.exec(url)[0].charAt(0), 
newUrl = url.replace(reExp, delimeter + 'hpr_id' + "=" + hrpid); 
window.location.href = newUrl; 

Questo è come ha funzionato per me.

2
//update URL Parameter 
function updateURL(key,val){ 
    var url = window.location.href; 
    var reExp = new RegExp("[\?|\&]"+key + "=[0-9a-zA-Z\_\+\-\|\.\,\;]*"); 

    if(reExp.test(url)) { 
     // update 
     var reExp = new RegExp("[\?&]" + key + "=([^&#]*)"); 
     var delimiter = reExp.exec(url)[0].charAt(0); 
     url = url.replace(reExp, delimiter + key + "=" + val); 
    } else { 
     // add 
     var newParam = key + "=" + val; 
     if(!url.indexOf('?')){url += '?';} 

     if(url.indexOf('#') > -1){ 
      var urlparts = url.split('#'); 
      url = urlparts[0] + "&" + newParam + (urlparts[1] ? "#" +urlparts[1] : ''); 
     } else { 
      url += "&" + newParam; 
     } 
    } 
    window.history.pushState(null, document.title, url); 
} 
+0

Questa è una funzione comoda, ma non funzionerà se l'url non ha parametri di query dall'inizio, ma hash un '#'. Puoi correggere questo problema cambiando la riga indexOf a '(url.indexOf ('?') === -1)' – leo

+0

(verrà anche visualizzato '? & Key = val', in caso di un solo url param) – leo

0

Un altro modo è che si può fare questo, utilizzando qualche semplice codice reg ex da Samuel Santos here come questo:

/* 
* queryParameters -> handles the query string parameters 
* queryString -> the query string without the fist '?' character 
* re -> the regular expression 
* m -> holds the string matching the regular expression 
*/ 
var queryParameters = {}, queryString = location.search.substring(1), 
     re = /([^&=]+)=([^&]*)/g, m; 

// Creates a map with the query string parameters 
while (m = re.exec(queryString)) { 
    queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); 
} 

// Update w and h 
queryParameters['w'] = 200; 
queryParameters['h'] = 200; 

Ora è possibile creare un nuovo URL:

var url = window.location.protocol + '//' + window.location.hostname + window.location.pathname; 

// Build new Query String 
var params = $.param(queryParameters); 
if (params != '') { 
    url = url + '?' + params; 
} 

OPPURE potresti utilizzare i parametri per ricaricare subito il browser:

location.search = params; 

o fare quello che vuoi con :)

0

Si potrebbe fare qualcosa di simile:

// If key exists updates the value 
if (location.href.indexOf('key=') > -1) { 
    location.href = location.href.replace('key=current_val', 'key=new_val'); 

// If not, append 
} else { 
    location.href = location.href + '&key=new_val'; 
} 

saluti

Problemi correlati