设置URL参数而不会导致页面刷新 [英] Set URL parameters without causing page refresh

查看:204
本文介绍了设置URL参数而不会导致页面刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 History.pushState()设置网址参数以避免浏览器刷新?如果有一个不简单的JS解决方案,是否已经有一个流行的库或jQuery的内置函数?

How can you set URL parameters using History.pushState() to avoid browser refreshes? If there is a not a simple JS solution, is there already a popular library or built in function for jQuery?

这是一个相关的SO问题,接受的答案是实际上并没有根据评论&我的测试(删除查询字符串而不是更新值): history.pushState()更改查询值

Here is a relevant SO question, where the accepted answer does not actually work according to comments & my test (it removes the query string instead of updating a value): history.pushState() change query values

为了清楚起见,我指的是查询字符串中的URL参数:
http:/ /google.com/page?name=don 因此我们可以将 don 更改为 tim 没有导致重新加载。

Just to be clear, I am referring to the URL parameters in a query string: http://google.com/page?name=don so we could change don to tim without causing a reload.

这是一种可能的解决方案我发现。但是我很担心使用只有2个粉丝的JS库:P

Here is one possible solution I found. However I'm nervous about using a JS library that only has 2 followers :P

推荐答案

你可以使用来自下面的小型图书馆的queryString.push('my_param_key','some_new_value')

它将使用历史记录更新您的URL参数.push,所以浏览器不会刷新。

It will update your URL param using history.push, so the browser will not refresh.

它只会影响您想要更改的参数,它会使路径和其他参数不受影响。

It will only affect the param you wish to change, it will leave the path and other params unaffected.

/*!
    query-string
    Parse and stringify URL query strings
    https://github.com/sindresorhus/query-string
    by Sindre Sorhus
    MIT License
*/
(function () {
    'use strict';
    var queryString = {};

    queryString.parse = function (str) {
        if (typeof str !== 'string') {
            return {};
        }

        str = str.trim().replace(/^\?/, '');

        if (!str) {
            return {};
        }

        return str.trim().split('&').reduce(function (ret, param) {
            var parts = param.replace(/\+/g, ' ').split('=');
            var key = parts[0];
            var val = parts[1];

            key = decodeURIComponent(key);
            // missing `=` should be `null`:
            // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
            val = val === undefined ? null : decodeURIComponent(val);

            if (!ret.hasOwnProperty(key)) {
                ret[key] = val;
            } else if (Array.isArray(ret[key])) {
                ret[key].push(val);
            } else {
                ret[key] = [ret[key], val];
            }

            return ret;
        }, {});
    };

    queryString.stringify = function (obj) {
        return obj ? Object.keys(obj).map(function (key) {
            var val = obj[key];

            if (Array.isArray(val)) {
                return val.map(function (val2) {
                    return encodeURIComponent(key) + '=' + encodeURIComponent(val2);
                }).join('&');
            }

            return encodeURIComponent(key) + '=' + encodeURIComponent(val);
        }).join('&') : '';
    };

    queryString.push = function (key, new_value) {
    var params = queryString.parse(location.search);
    params[key] = new_value;
    var new_params_string = queryString.stringify(params)
    history.pushState({}, "", window.location.pathname + '?' + new_params_string);
  }

    if (typeof module !== 'undefined' && module.exports) {
        module.exports = queryString;
    } else {
        window.queryString = queryString;
    }
})();

这篇关于设置URL参数而不会导致页面刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆