【问题标题】:Remove the query string before appending the url parameters在附加 url 参数之前删除查询字符串
【发布时间】:2018-05-02 16:17:30
【问题描述】:

我想在添加 URL 参数之前从 URL 中删除查询字符串。假设我的网站是 https://www.abcd.com/test 我正在通过 javascript 向我的 URL 附加一些参数,例如 /def?key=value。但是页面构建为https://www.abcd.com/test?/def?key=value。我希望它是https://www.abcd.com/test/def?key=value 下面是我的代码。非常感谢任何输入。

redirectURL: function() {
    var currentURL = window.location.href;

    var kvp = document.location.search.substr(1).split('&');
    if (kvp == '') {
        if (currentURL.indexOf("def") == -1){ 
            document.location.search = '/def'+ '?' + 'key' + '=' + 'value';
        }else{
            document.location.search = '?' + 'key' + '=' + 'value';
        }
    }
    else {
        var i = kvp.length; var x; while (i--) {
            x = kvp[i].split('=');

            if (x[0] == key) {
                x[1] = value;
                kvp[i] = x.join('=');
                break;
            }
        }

        if (i < 0) { kvp[kvp.length] = [key, value].join('='); }

        document.location.search = kvp.join('&');
    }
}

【问题讨论】:

    标签: javascript jquery html query-string


    【解决方案1】:

    您将 URL 参数 附加到作为查询字符串的 location.search 属性:

    document.location.search = '/def'+ '?' + 'key' + '=' + 'value';
    

    我相信您想要做的是将您的 URL 参数 附加到 location.href 属性,但首先您需要将现有的 search 字符串(查询字符串)与其分开:

    var urlBase = window.location.href.split('?')[0];
    window.location.href = urlBase + '/def'+ '?' + 'key' + '=' + 'value';
    

    【讨论】:

      猜你喜欢
      • 2013-07-20
      • 2017-05-22
      • 2022-01-22
      • 1970-01-01
      • 2011-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-05
      相关资源
      最近更新 更多