【问题标题】:How to store program state in URL query string?如何在 URL 查询字符串中存储程序状态?
【发布时间】:2013-05-27 23:14:36
【问题描述】:

如何读取、和写入到查询字符串?

var pageNumber = QueryString['pageNumber'];
var pageSize   = QueryString['pageSize'];

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

function refresh() { /** get data and update page here **/ }

当然,这将允许用户复制和粘贴包含部分程序状态的 URL。

有没有类似QueryString(上面用过)的API?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

正如 Richard 所说,通过分配给 window.location.search 来更改查询字符串将触发页面重新加载。

因此,通常的做法是在片段标识符中编码客户端状态(“哈希路由”,与旧版浏览器兼容)或使用history.pushState(HTML5 的一部分)来操作路径。 pushState 需要服务器端支持,通常采用通配符路由的形式。

DirectorBackbone Router 等库提供适用于任一技术的抽象。

更新 在对这个答案进行研究之前,我不知道这一点,但是可以通过 pushState 操作查询字符串(考虑到它是 URL 的一部分,这是有道理的)。正如this demo 的作者所指出的,这允许在没有任何特殊服务器端支持的情况下使用 pushState。

【讨论】:

    【解决方案2】:

    浏览器内 JavaScript 可以使用浏览对象模型的 window.location.search 属性访问查询字符串。但是,解析该查询字符串的本地支持并不多。 (另见How can I get a specific parameter from location.search?

    也许这样的事情会做?

    var GET = {}; // 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 necessary
        var paramValue = keyValuePair.replace(/^[^=]*\=/, ""); // some decoding is probably necessary
        GET[paramName] = paramValue;
    });
    
    var pageNumber = GET['pageNumber']?Number(GET['pageNumber']):0;
    
    $('#next').click(function() { 
        GET['pageNumber'] = ++pageNumber;
        refresh(); 
    });
    
    function refresh() {
        var newQueryString = Object.keys(GET).reduce(function(keyValuePairs, paramName) {
            keyValuePairs.push(escape(paramName)+"="+escape(GET[paramName]));
            return keyValuePairs;
        }, []).join('&');
    
        window.location.search = "?"+newQueryString;
    }
    

    【讨论】:

    • 调用window.location.search不会触发页面加载吗?
    • @landon9720 - 这取决于你所说的“打电话”是什么意思。读取该值不会触发页面加载;写信给它。如果您不希望在不触发页面加载的情况下更改 window.location.hash 值(对应于 Fragment Identifier)。
    猜你喜欢
    • 2020-02-13
    • 2011-09-03
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    相关资源
    最近更新 更多