Jak Mogę dodać lub zaktualizować parametr ciągu zapytania?

Z javascript jak Mogę dodać parametr query string do adresu url, jeśli nie jest obecny lub jeśli jest obecny, zaktualizuj bieżącą wartość? Używam jquery do rozwoju po stronie klienta.

Author: Liam, 2011-05-14

22 answers

Napisałem następującą funkcję, która realizuje to, co chcę osiągnąć:

function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
  var separator = uri.indexOf('?') !== -1 ? "&" : "?";
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + "=" + value + '$2');
  }
  else {
    return uri + separator + key + "=" + value;
  }
}
 414
Author: amateur,
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-03-21 10:55:11

Rozszerzyłem rozwiązanie i połączyłem je z innym, który znalazłem, aby zastąpić / zaktualizować/usunąć parametry querystring na podstawie danych wejściowych użytkowników i biorąc pod uwagę kotwicę adresów URL.

Nie podanie wartości spowoduje usunięcie parametru, podanie jednej spowoduje dodanie / aktualizację parametru. Jeśli nie podano adresu URL, zostanie on pobrany z okna.lokalizacja

function UpdateQueryString(key, value, url) {
    if (!url) url = window.location.href;
    var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
        hash;

    if (re.test(url)) {
        if (typeof value !== 'undefined' && value !== null)
            return url.replace(re, '$1' + key + "=" + value + '$2$3');
        else {
            hash = url.split('#');
            url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) 
                url += '#' + hash[1];
            return url;
        }
    }
    else {
        if (typeof value !== 'undefined' && value !== null) {
            var separator = url.indexOf('?') !== -1 ? '&' : '?';
            hash = url.split('#');
            url = hash[0] + separator + key + '=' + value;
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) 
                url += '#' + hash[1];
            return url;
        }
        else
            return url;
    }
}

Update

Wystąpił błąd przy usuwaniu pierwszego parametru w zapytaniu, mam przerobiono wyrażenia regularne i test, aby uwzględnić poprawkę.

Druga Aktualizacja

Zgodnie z sugestią @JarónBarends-sprawdź wartość Tweak, aby sprawdzić przed undefined i null, aby zezwolić na ustawienie wartości 0

Trzecia Aktualizacja

Wystąpił błąd, który powodował, że usunięcie zmiennej querystring bezpośrednio przed hashtagiem powodowało utratę symbolu hashtagu, który został naprawiony

Czwarta Aktualizacja

Dzięki @rooby za wskazanie optymalizacji wyrażeń regularnych w pierwszym wyrażeniu regularnym obiekt. Ustaw początkowe Wyrażenie regularne na ([?& ]) z powodu problemów z używaniem (\?/ & ) found by @ YonatanKarni

Piąta Aktualizacja

Usunięcie deklaracji hash var w instrukcji if / else

 168
Author: ellemayo,
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
2018-02-16 19:59:20

Narzędzie URLSearchParams może być do tego przydatne w połączeniu z window.location.search. Na przykład:

if ('URLSearchParams' in window) {
    var searchParams = new URLSearchParams(window.location.search);
    searchParams.set("foo", "bar");
    window.location.search = searchParams.toString();
}

Teraz foo został ustawiony na bar niezależnie od tego, czy już istniał.

Powyższe przypisanie do window.location.search spowoduje załadowanie strony, więc jeśli nie jest to pożądane, użyj History API w następujący sposób:

if ('URLSearchParams' in window) {
    var searchParams = new URLSearchParams(window.location.search)
    searchParams.set("foo", "bar");
    var newRelativePathQuery = window.location.pathname + '?' + searchParams.toString();
    history.pushState(null, '', newRelativePathQuery);
}

Teraz nie musisz pisać własnych regex lub logiki, aby obsłużyć ewentualne istnienie ciągów zapytań.

Jednak obsługa przeglądarki jest słaba, ponieważ jest obecnie eksperymentalna i używana tylko w najnowszych wersjach Chrome, Firefox, Safari, iOS Safari, Android Browser, Android Chrome i Opera. Użyj z polyfill , jeśli zdecydujesz się go użyć.

Aktualizacja: obsługa przeglądarki poprawiła się od czasu mojej pierwotnej odpowiedzi.

 42
Author: Anthony Manning-Franklin,
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-07-25 05:30:24

Na podstawie odpowiedzi @amateur (a teraz włączenie poprawki z komentarza @j_walker_dev), ale biorąc pod uwagę komentarz o hash tagach w adresie URL używam następującego:

function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|#|$)", "i");
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + "=" + value + '$2');
  } else {
    var hash =  '';
    if( uri.indexOf('#') !== -1 ){
        hash = uri.replace(/.*#/, '#');
        uri = uri.replace(/#.*/, '');
    }
    var separator = uri.indexOf('?') !== -1 ? "&" : "?";    
    return uri + separator + key + "=" + value + hash;
  }
}

Edited to fix [?|&] in regex which should of course be [?&] Jak wskazano w komentarzach

Edit: alternatywna wersja do obsługi usuwania param URL, jak również. Użyłem value === undefined jako sposobu wskazania usunięcia. Może używać value === false lub nawet oddzielnego wejścia param jak chciał.

function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|#|$)", "i");
  if( value === undefined ) {
    if (uri.match(re)) {
        return uri.replace(re, '$1$2');
    } else {
        return uri;
    }
  } else {
    if (uri.match(re)) {
        return uri.replace(re, '$1' + key + "=" + value + '$2');
    } else {
    var hash =  '';
    if( uri.indexOf('#') !== -1 ){
        hash = uri.replace(/.*#/, '#');
        uri = uri.replace(/#.*/, '');
    }
    var separator = uri.indexOf('?') !== -1 ? "&" : "?";    
    return uri + separator + key + "=" + value + hash;
  }
  }  
}

Zobacz it w akcji na https://jsfiddle.net/bp3tmuxh/1/

 39
Author: Adam,
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-01-04 14:18:26

Oto moja biblioteka, aby to zrobić: https://github.com/Mikhus/jsurl

var u = new Url;
u.query.param='value'; // adds or replaces the param
alert(u)
 19
Author: Mikhus,
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-04-19 07:37:32

Okno.miejsce.Wyszukiwanie to Odczyt/Zapis.

Jednak-modyfikacja ciągu zapytania spowoduje przekierowanie strony, na której się znajdujesz i spowoduje odświeżenie z serwera.

Jeśli to, co próbujesz zrobić, to utrzymać stan po stronie klienta (i potencjalnie uczynić go zakładką-stanie), będziesz chciał zmodyfikować hash adresu URL zamiast ciągu zapytania, który utrzymuje Cię na tej samej stronie (okno.miejsce.hash to read/write). Tak właśnie strony internetowe lubią twitter.com zrób to.

Będziesz też chciał tył przycisk do pracy, będziesz musiał powiązać zdarzenia javascript ze zdarzeniem hash change, dobrym pluginem do tego jest http://benalman.com/projects/jquery-hashchange-plugin/

 10
Author: Gal,
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-05-14 07:20:31

Oto moje podejście: funkcja location.params() (pokazana poniżej) może być używana jako getter lub setter. Przykłady:

Podany adres URL to http://example.com/?foo=bar&baz#some-hash,

  1. location.params() zwróci obiekt ze wszystkimi parametrami zapytania: {foo: 'bar', baz: true}.
  2. location.params('foo') zwróci 'bar'.
  3. location.params({foo: undefined, hello: 'world', test: true}) zmieni adres URL na http://example.com/?baz&hello=world&test#some-hash.

Tutaj znajduje się funkcja params(), którą opcjonalnie można przypisać do obiektu window.location.

location.params = function(params) {
  var obj = {}, i, parts, len, key, value;

  if (typeof params === 'string') {
    value = location.search.match(new RegExp('[?&]' + params + '=?([^&]*)[&#$]?'));
    return value ? value[1] : undefined;
  }

  var _params = location.search.substr(1).split('&');

  for (i = 0, len = _params.length; i < len; i++) {
    parts = _params[i].split('=');
    if (! parts[0]) {continue;}
    obj[parts[0]] = parts[1] || true;
  }

  if (typeof params !== 'object') {return obj;}

  for (key in params) {
    value = params[key];
    if (typeof value === 'undefined') {
      delete obj[key];
    } else {
      obj[key] = value;
    }
  }

  parts = [];
  for (key in obj) {
    parts.push(key + (obj[key] === true ? '' : '=' + obj[key]));
  }

  location.search = parts.join('&');
};
 9
Author: jake,
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
2015-01-25 03:05:39

Jeśli nie jest ustawiony lub chcesz zaktualizować o nową wartość, możesz użyć:

window.location.search = 'param=value'; // or param=new_value

To jest w prostym Javascript, tak przy okazji.

EDIT

Możesz spróbować użyć wtyczki jquery query-object

Okno.miejsce./ align = "left" / jQuery.zapytanie.set ("param", 5);

 9
Author: tradyblix,
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
2015-12-14 23:51:35

To jest moja preferencja i obejmuje sprawy, które mogę wymyślić. Czy ktoś może wymyślić sposób na zredukowanie go do jednej wymiany?

function setParam(uri, key, val) {
    return uri
        .replace(RegExp("([?&]"+key+"(?=[=&#]|$)[^#&]*|(?=#|$))"), "&"+key+"="+encodeURIComponent(val))
        .replace(/^([^?&]+)&/, "$1?");
}
 6
Author: Adam Leggett,
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
2016-11-30 21:15:18

Zdaję sobie sprawę, że to pytanie jest stare i zostało udzielone na śmierć, ale oto moje zadanie. Staram się tu na nowo odkryć koło, ponieważ korzystałem z aktualnie akceptowanej odpowiedzi, a niewłaściwe używanie fragmentów URL ostatnio ugryzło mnie w projekcie.

Funkcja jest poniżej. Jest dość długi, ale został wykonany tak, aby był jak najbardziej wytrzymały. Chciałbym sugestie dotyczące skrócenia/poprawy. Przygotowałem dla niego mały zestaw testów jsFiddle (lub inne podobne funkcje). Jeśli a funkcja może przejść każdy z testów tam, mówię, że prawdopodobnie jest dobry, aby przejść.

Update: natknąłem się na fajną funkcję używającą DOM do parsowania adresów URL , więc włączyłem tę technikę tutaj. To sprawia, że funkcja jest krótsza i bardziej niezawodna. Rekwizyty do autora tej funkcji.

/**
 * Add or update a query string parameter. If no URI is given, we use the current
 * window.location.href value for the URI.
 * 
 * Based on the DOM URL parser described here:
 * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
 *
 * @param   (string)    uri     Optional: The URI to add or update a parameter in
 * @param   (string)    key     The key to add or update
 * @param   (string)    value   The new value to set for key
 *
 * Tested on Chrome 34, Firefox 29, IE 7 and 11
 */
function update_query_string( uri, key, value ) {

    // Use window URL if no query string is provided
    if ( ! uri ) { uri = window.location.href; }

    // Create a dummy element to parse the URI with
    var a = document.createElement( 'a' ), 

        // match the key, optional square bracktes, an equals sign or end of string, the optional value
        reg_ex = new RegExp( key + '((?:\\[[^\\]]*\\])?)(=|$)(.*)' ),

        // Setup some additional variables
        qs,
        qs_len,
        key_found = false;

    // Use the JS API to parse the URI 
    a.href = uri;

    // If the URI doesn't have a query string, add it and return
    if ( ! a.search ) {

        a.search = '?' + key + '=' + value;

        return a.href;
    }

    // Split the query string by ampersands
    qs = a.search.replace( /^\?/, '' ).split( /&(?:amp;)?/ );
    qs_len = qs.length; 

    // Loop through each query string part
    while ( qs_len > 0 ) {

        qs_len--;

        // Check if the current part matches our key
        if ( reg_ex.test( qs[qs_len] ) ) {

            // Replace the current value
            qs[qs_len] = qs[qs_len].replace( reg_ex, key + '$1' ) + '=' + value;

            key_found = true;
        }
    }   

    // If we haven't replaced any occurences above, add the new parameter and value
    if ( ! key_found ) { qs.push( key + '=' + value ); }

    // Set the new query string
    a.search = '?' + qs.join( '&' );

    return a.href;
}
 5
Author: Dominic P,
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-05-12 21:22:08

Wiem, że jest to dość stare, ale chcę tutaj umieścić moją działającą wersję .

function addOrUpdateUrlParam(uri, paramKey, paramVal) {
  var re = new RegExp("([?&])" + paramKey + "=[^&#]*", "i");
  if (re.test(uri)) {
    uri = uri.replace(re, '$1' + paramKey + "=" + paramVal);
  } else {
    var separator = /\?/.test(uri) ? "&" : "?";
    uri = uri + separator + paramKey + "=" + paramVal;
  }
  return uri;
}

jQuery(document).ready(function($) {
  $('#paramKey,#paramValue').on('change', function() {
    if ($('#paramKey').val() != "" && $('#paramValue').val() != "") {
      $('#uri').val(addOrUpdateUrlParam($('#uri').val(), $('#paramKey').val(), $('#paramValue').val()));
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="width:100%" type="text" id="uri" value="http://www.example.com/text.php">
<label style="display:block;">paramKey
  <input type="text" id="paramKey">
</label>
<label style="display:block;">paramValue
  <input type="text" id="paramValue">
</label>

Uwaga jest to zmodyfikowana wersja @elreimundo

 5
Author: Paolo Falomo,
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
2016-05-10 14:33:33

Moje ujęcie stąd (Zgodne z "use strict"; tak naprawdę nie używa jQuery):

function decodeURIParams(query) {
  if (query == null)
    query = window.location.search;
  if (query[0] == '?')
    query = query.substring(1);

  var params = query.split('&');
  var result = {};
  for (var i = 0; i < params.length; i++) {
    var param = params[i];
    var pos = param.indexOf('=');
    if (pos >= 0) {
        var key = decodeURIComponent(param.substring(0, pos));
        var val = decodeURIComponent(param.substring(pos + 1));
        result[key] = val;
    } else {
        var key = decodeURIComponent(param);
        result[key] = true;
    }
  }
  return result;
}

function encodeURIParams(params, addQuestionMark) {
  var pairs = [];
  for (var key in params) if (params.hasOwnProperty(key)) {
    var value = params[key];
    if (value != null) /* matches null and undefined */ {
      pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
    }
  }
  if (pairs.length == 0)
    return '';
  return (addQuestionMark ? '?' : '') + pairs.join('&');
}

//// alternative to $.extend if not using jQuery:
// function mergeObjects(destination, source) {
//   for (var key in source) if (source.hasOwnProperty(key)) {
//     destination[key] = source[key];
//   }
//   return destination;
// }

function navigateWithURIParams(newParams) {
  window.location.search = encodeURIParams($.extend(decodeURIParams(), newParams), true);
}

Przykładowe użycie:

// add/update parameters
navigateWithURIParams({ foo: 'bar', boz: 42 });

// remove parameter
navigateWithURIParams({ foo: null });

// submit the given form by adding/replacing URI parameters (with jQuery)
$('.filter-form').submit(function(e) {
  e.preventDefault();
  navigateWithURIParams(decodeURIParams($(this).serialize()));
});
 2
Author: Andrey Tarantsov,
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-02-05 03:37:52

Bazując na odpowiedzi @ellemayo, wymyśliłem następujące rozwiązanie, które pozwala na wyłączenie tagu hash w razie potrzeby:

function updateQueryString(key, value, options) {
    if (!options) options = {};

    var url = options.url || location.href;
    var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"), hash;

    hash = url.split('#');
    url = hash[0];
    if (re.test(url)) {
        if (typeof value !== 'undefined' && value !== null) {
            url = url.replace(re, '$1' + key + "=" + value + '$2$3');
        } else {
            url = url.replace(re, '$1$3').replace(/(&|\?)$/, '');
        }
    } else if (typeof value !== 'undefined' && value !== null) {
        var separator = url.indexOf('?') !== -1 ? '&' : '?';
        url = url + separator + key + '=' + value;
    }

    if ((typeof options.hash === 'undefined' || options.hash) &&
        typeof hash[1] !== 'undefined' && hash[1] !== null)
        url += '#' + hash[1];
    return url;
}

Nazwij to tak:

updateQueryString('foo', 'bar', {
    url: 'http://my.example.com#hash',
    hash: false
});

Wyniki w:

http://my.example.com?foo=bar
 2
Author: RuubW,
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
2015-06-24 07:56:14

Oto krótsza wersja, która zajmuje się

  • zapytanie z podanym parametrem lub bez
  • zapytanie z wieloma wartościami parametrów
  • zapytanie zawierające hash

Kod:

var setQueryParameter = function(uri, key, value) {
  var re = new RegExp("([?&])("+ key + "=)[^&#]*", "g");
  if (uri.match(re)) 
    return uri.replace(re, '$1$2' + value);

  // need to add parameter to URI
  var paramString = (uri.indexOf('?') < 0 ? "?" : "&") + key + "=" + value;
  var hashIndex = uri.indexOf('#');
  if (hashIndex < 0)
    return uri + paramString;
  else
    return uri.substring(0, hashIndex) + paramString + uri.substring(hashIndex);
}

Opis regex można znaleźć tutaj .

Uwaga: To rozwiązanie jest oparte na @amateur answer, ale z wieloma ulepszeniami.

 2
Author: MaxZoom,
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
2016-09-27 13:58:56

Inne podejście bez użycia wyrażeń regularnych . Obsługuje anchory "hash" na końcu adresu url, a także wiele znaków zapytania (?). Powinno być nieco szybsze niż podejście do wyrażeń regularnych.

function setUrlParameter(url, key, value) {
  var parts = url.split("#", 2), anchor = parts.length > 1 ? "#" + parts[1] : '';
  var query = (url = parts[0]).split("?", 2);
  if (query.length === 1) 
    return url + "?" + key + "=" + value + anchor;

  for (var params = query[query.length - 1].split("&"), i = 0; i < params.length; i++)
    if (params[i].toLowerCase().startsWith(key.toLowerCase() + "="))
      return params[i] = key + "=" + value, query[query.length - 1] = params.join("&"), query.join("?") + anchor;

  return url + "&" + key + "=" + value + anchor
}
 1
Author: cwills,
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-04-22 08:30:38

Aby podać przykład kodu modyfikującego window.location.search zgodnie z sugestią Gal i tradyblixa:

var qs = window.location.search || "?";
var param = key + "=" + value; // remember to URI encode your parameters
if (qs.length > 1) {
    // more than just the question mark, so append with ampersand
    qs = qs + "&";
}
qs = qs + param;
window.location.search = qs;
 0
Author: Risadinha,
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-06-19 16:26:48

Kod Java script, aby znaleźć określony ciąg zapytania i zastąpić jego wartość *

('input.letter').click(function () {
                //0- prepare values
                var qsTargeted = 'letter=' + this.value; //"letter=A";
                var windowUrl = '';
                var qskey = qsTargeted.split('=')[0];
                var qsvalue = qsTargeted.split('=')[1];
                //1- get row url
                var originalURL = window.location.href;
                //2- get query string part, and url
                if (originalURL.split('?').length > 1) //qs is exists
                {
                    windowUrl = originalURL.split('?')[0];
                    var qs = originalURL.split('?')[1];
                    //3- get list of query strings
                    var qsArray = qs.split('&');
                    var flag = false;
                    //4- try to find query string key
                    for (var i = 0; i < qsArray.length; i++) {
                        if (qsArray[i].split('=').length > 0) {
                            if (qskey == qsArray[i].split('=')[0]) {
                                //exists key
                                qsArray[i] = qskey + '=' + qsvalue;
                                flag = true;
                                break;
                            }
                        }
                    }
                    if (!flag)//   //5- if exists modify,else add
                    {
                        qsArray.push(qsTargeted);
                    }
                    var finalQs = qsArray.join('&');
                    //6- prepare final url
                    window.location = windowUrl + '?' + finalQs;
                }
                else {
                    //6- prepare final url
                    //add query string
                    window.location = originalURL + '?' + qsTargeted;
                }
            })
        });
 0
Author: Mohamed.Abdo,
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-06-25 12:17:03

Tak, miałem problem, w którym moje querystring przepełni się i powieli, ale było to spowodowane moją własną powolnością. więc grałem trochę i nadrobiłem trochę JS jquery (faktycznie) i C # magick.

Więc właśnie zdałem sobie sprawę, że po serwer zrobił z przekazanymi wartościami, wartości już nie ma znaczenia, nie ma ponownego użycia, jeśli klient chciał zrobić to samo widocznie zawsze będzie nowe żądanie, nawet jeśli jego te same parametry są przekazywane. I to wszystko klient, więc niektóre buforowanie / ciasteczka itp. mogą być fajne pod tym względem.

JS:

$(document).ready(function () {
            $('#ser').click(function () {
                SerializeIT();
            });
            function SerializeIT() {
                var baseUrl = "";
                baseUrl = getBaseUrlFromBrowserUrl(window.location.toString());
                var myQueryString = "";
                funkyMethodChangingStuff(); //whatever else before serializing and creating the querystring
                myQueryString = $('#fr2').serialize();
                window.location.replace(baseUrl + "?" + myQueryString);
            }
            function getBaseUrlFromBrowserUrl(szurl) {
                return szurl.split("?")[0];
            } 
            function funkyMethodChangingStuff(){
               //do stuff to whatever is in fr2
            }
        });

HTML:

<div id="fr2">
   <input type="text" name="qURL" value="http://somewhere.com" />
   <input type="text" name="qSPart" value="someSearchPattern" />
</div>
<button id="ser">Serialize! and go play with the server.</button>

C#:

    using System.Web;
    using System.Text;
    using System.Collections.Specialized;

    public partial class SomeCoolWebApp : System.Web.UI.Page
    {
        string weburl = string.Empty;
        string partName = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            string loadurl = HttpContext.Current.Request.RawUrl;
            string querySZ = null;
            int isQuery = loadurl.IndexOf('?');
            if (isQuery == -1) { 
                //If There Was no Query
            }
            else if (isQuery >= 1) {
                querySZ = (isQuery < loadurl.Length - 1) ? loadurl.Substring(isQuery + 1) : string.Empty;
                string[] getSingleQuery = querySZ.Split('?');
                querySZ = getSingleQuery[0];

                NameValueCollection qs = null;
                qs = HttpUtility.ParseQueryString(querySZ);

                weburl = qs["qURL"];
                partName = qs["qSPart"];
                //call some great method thisPageRocks(weburl,partName); or whatever.
          }
      }
  }

ok krytyka jest mile widziana(to była nocna mikstura, więc nie krępuj się zauważyć zmian). Jeśli to w ogóle pomogło, kciuk w górę, szczęśliwe kodowanie.

Brak duplikatów, każde żądanie tak unikalne, jak je zmodyfikowałeś, a ze względu na jego strukturę, łatwo dodawać dynamicznie więcej zapytań z dom.

 0
Author: LokizFenrir,
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-09-01 17:36:11

Oto alternatywna metoda wykorzystująca wbudowane właściwości elementu anchor HTML:

  • obsługuje parametry wielowartościowe.
  • Brak ryzyka modyfikacji fragmentu # lub czegokolwiek innego niż sam ciąg zapytania.
  • Może być trochę łatwiejsze do odczytania? Ale jest dłuższy.

    var a = document.createElement('a'),

	getHrefWithUpdatedQueryString = function(param, value) {
	    return updatedQueryString(window.location.href, param, value);
	},

	updatedQueryString = function(url, param, value) {
	    /*
	     A function which modifies the query string 
             by setting one parameter to a single value.

	     Any other instances of parameter will be removed/replaced.
	     */
	    var fragment = encodeURIComponent(param) + 
                           '=' + encodeURIComponent(value);

	    a.href = url;

	    if (a.search.length === 0) {
		a.search = '?' + fragment;
	    } else {
		var didReplace = false,
		    // Remove leading '?'
		    parts = a.search.substring(1)
		// Break into pieces
			.split('&'),

		    reassemble = [],
		    len = parts.length;

		for (var i = 0; i < len; i++) {
		    
		    var pieces = parts[i].split('=');
		    if (pieces[0] === param) {
			if (!didReplace) {
			    reassemble.push('&' + fragment);
			    didReplace = true;
			}
		    } else {
			reassemble.push(parts[i]);
		    }
		}

		if (!didReplace) {
		    reassemble.push('&' + fragment);
		}

		a.search = reassemble.join('&');
	    }

	    return a.href;
	};
 0
Author: GlennS,
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
2015-09-04 13:22:14

Jeśli chcesz ustawić kilka parametrów na raz:

function updateQueryStringParameters(uri, params) {
    for(key in params){
      var value = params[key],
          re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"),
          separator = uri.indexOf('?') !== -1 ? "&" : "?";
      if (uri.match(re)) {
        uri = uri.replace(re, '$1' + key + "=" + value + '$2');
      }
      else {
        uri = uri + separator + key + "=" + value;
      }
    }
    return uri;
}

Ta sama funkcja co @ amator ' s

Jeśli jslint wyświetli błąd dodaj to po pętli for

if(params.hasOwnProperty(key))
 0
Author: Rachid Oussanaa,
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
2015-11-27 10:47:57

Na tej stronie jest wiele niezręcznych i niepotrzebnie skomplikowanych odpowiedzi. Najwyżej oceniany, @ amator, jest całkiem dobry, chociaż ma trochę niepotrzebnego puchu w wyrażeniu regularnym. Poniżej znajduje się nieco bardziej optymalne rozwiązanie z wyrażeniem RegExp cleaner i wywołaniem cleaner replace:

function updateQueryStringParamsNoHash(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=[^&]*", "i");
  return re.test(uri)
       ? uri.replace(re, '$1' + key + "=" + value)
       : uri + separator + key + "=" + value
  ;
}

Jako dodatkowy bonus, jeśli uri nie jest ciągiem znaków, nie otrzymasz błędów za próbę wywołania match lub replace na czymś, co może nie zaimplementować tych metod.

I jeśli chcesz zająć się sprawą hash (i już sprawdziłeś poprawnie sformatowany HTML), możesz wykorzystać istniejącą funkcję zamiast pisać nową funkcję zawierającą tę samą logikę:

function updateQueryStringParams(url, key, value) {
    var splitURL = url.split('#');
    var hash = splitURL[1];
    var uri = updateQueryStringParamsNoHash(splitURL[0]);
    return hash == null ? uri : uri + '#' + hash;
}

Albo możesz wprowadzić kilka drobnych zmian do @Adam ' s skądinąd doskonałej odpowiedzi:

function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=[^&#]*", "i");
  if (re.test(uri)) {
    return uri.replace(re, '$1' + key + "=" + value);
  } else {
    var matchData = uri.match(/^([^#]*)(#.*)?$/);
    var separator = /\?/.test(uri) ? "&" : "?";    
    return matchData[0] + separator + key + "=" + value + (matchData[1] || '');
  }
}
 0
Author: elreimundo,
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
2016-05-10 14:32:42

Powinno to służyć celowi:

function updateQueryString(url, key, value) {
    var arr =  url.split("#");
    var url = arr[0];
    var fragmentId = arr[1];
    var updatedQS = "";
    if (url.indexOf("?") == -1) {
        updatedQS = encodeURIComponent(key) + "=" + encodeURIComponent(value);
    }
    else {
        updatedQS = addOrModifyQS(url.substring(url.indexOf("?") + 1), key, value); 
    }
    url = url.substring(0, url.indexOf("?")) + "?" + updatedQS;
    if (typeof fragmentId !== 'undefined') {
        url = url + "#" + fragmentId;
    }
    return url;
}

function addOrModifyQS(queryStrings, key, value) {
    var oldQueryStrings = queryStrings.split("&");
    var newQueryStrings = new Array();
    var isNewKey = true;
    for (var i in oldQueryStrings) {
        var currItem = oldQueryStrings[i];
        var searchKey = key + "=";
        if (currItem.indexOf(searchKey) != -1) {
            currItem = encodeURIComponent(key) + "=" + encodeURIComponent(value);
            isNewKey = false;
        }
        newQueryStrings.push(currItem);
    }
    if (isNewKey) {
        newQueryStrings.push(encodeURIComponent(key) + "=" + encodeURIComponent(value));
    }
    return newQueryStrings.join("&");
}   
 0
Author: mmuzahid,
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
2016-12-02 09:14:05