Skip to content Skip to sidebar Skip to footer

How To Store Program State In Url Query String?

How do I read, and write, to the query string? var pageNumber = QueryString['pageNumber']; var pageSize = QueryString['pageSize']; $('#next').click(function() { QueryString

Solution 1:

As Richard mentioned, changing the query string by assigning to window.location.search will trigger a page reload.

For this reason, it is common practice to instead encode client-side state in the fragment identifier ("hash routing", which is compatible with older browsers) or to manipulate the path using history.pushState (part of HTML5). pushState requires serverside support, which usually takes the form of a wildcard route.

Libraries such as Director or Backbone Router provide abstractions that will work with either technique.

Update I didn't know this until doing research for this answer, but it is possible to manipulate the query string via pushState (which makes sense given that it's part of the URL). As the author of this demo points out, this allows using pushState without any special serverside support.

Solution 2:

In-browser JavaScript can access the query string using the Browse Object Model's window.location.search property. There isn't a lot of native support for parsing that query string though. (see also How can I get a specific parameter from location.search?)

Perhaps something like this will do?

varGET = {}; // I've taken the liberty of re-naming your `QueryString` object// to just `GET`, kind of in the style of PHP.// Mostly because I find it confusing to refer to something which// is not a string (it is an object/map) as a string.var queryString = window.location.search.replace(/^\?/, ''); // but this: *this* is a string!
queryString.split(/\&/).forEach(function(keyValuePair) {
    var paramName = keyValuePair.replace(/=.*$/, ""); // some decoding is probably necessaryvar paramValue = keyValuePair.replace(/^[^=]*\=/, ""); // some decoding is probably necessaryGET[paramName] = paramValue;
});

var pageNumber = GET['pageNumber']?Number(GET['pageNumber']):0;

$('#next').click(function() { 
    GET['pageNumber'] = ++pageNumber;
    refresh(); 
});

functionrefresh() {
    var newQueryString = Object.keys(GET).reduce(function(keyValuePairs, paramName) {
        keyValuePairs.push(escape(paramName)+"="+escape(GET[paramName]));
        return keyValuePairs;
    }, []).join('&');

    window.location.search = "?"+newQueryString;
}

Post a Comment for "How To Store Program State In Url Query String?"