添加或更新查询字符串参数 - URL保持不变

时间:2014-02-14 16:12:11

标签: javascript

我正在使用此代码块来管理查询字符串参数:

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

    if (re.test(url)) {
        if (typeof value !== 'undefined' && value !== null)
            return url.replace(re, '$1' + key + "=" + value + '$2$3');
        else {
            var 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;
    }
}

功能来源:add or update query string parameter

我正在调用该函数,一切运行正常但我的浏览器上的url没有更改。我还使用Chrome控制台检查功能是否正确调用且功能正常并返回预期值但网址保持不变。

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

此功能不会更改网址。它只是返回一个字符串。

如果您想更改网址(重新加载页面),您应该写下这样的内容:

window.location.href = UpdateQueryString(your_key, your_value, your_url)

如果您想更改网址而不重新加载整个网页,请使用HTML5历史记录/状态API,您可能对此感兴趣:

https://github.com/browserstate/history.js/

答案 1 :(得分:1)

关键是这个函数不会改变url,你应该自己这样做:

 window.location.href = UpdateQueryString("yourkey","newvalue");

或改为:

function UpdateQueryString(key, value, url) {
    //this flag is to check if you want to change the current page url
    var iscurrentpage = false;
    if (!url){
        url = window.location.href;
        iscurrentpage = true;
    }
    var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi");

    //this variable would be used as the result for this function
    var result = null;

    if (re.test(url)) {
        if (typeof value !== 'undefined' && value !== null) result = url.replace(re, '$1' + key + "=" + value + '$2$3');
        else {
            var hash = url.split('#');
            url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) url += '#' + hash[1];
            result = 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];
            result = url;
        } else result = url;
    }
    //if this is current page update the current page url
    if(iscurrentpage) window.location.href = result;
    return result;
}

然后在没有url参数的情况下调用它,只需使用2个参数:

UpdateQueryString("yourkey", "newvalue");
相关问题