【问题标题】:jQuery - Automatically add query string parameterjQuery - 自动添加查询字符串参数
【发布时间】:2015-05-26 08:56:40
【问题描述】:

我需要一个脚本来自动将ffv 查询字符串参数添加到我网站上的所有页面,如下例所示:

mywebsite.com?ffv

mywebsite.com/page?ffv

mywebsite.com/basket?ffv

【问题讨论】:

  • 当您说“所有 url”时,您是指仅在 a 元素中的那些,还是包括 form 元素和 background-images 等上的 action 属性?
  • 我指的是物理页面,而不是页面元素
  • @gdjc 为了简单起见:您的意思是浏览器中 url 栏中的 url,对吗?您希望它们自动附加“?ffv”,对吗?
  • @clami219 - 是的,浏览器栏中的所有 URL 都附有上述字符串。

标签: jquery url query-string


【解决方案1】:

网址是-https://mywebsite.com/path?ffv#hash

http[s]:// - protocol <br>
mywebsite.com - domain <br>
/path - path <br> 
?ffv - query string <br>
\#value - hash

如果您需要更改查询字符串,请尝试 JavaScript window.location 对象 变更查询:

function replace_search(value) {

    "use strict";

    if (typeof value === 'string' || typeof value === 'number') {
        window.location.search = value;
    }

}

在页面侧你猫使用 onclick 事件进行手动更改:

    <button onclick="replace_search('query')">got to query</button>

【讨论】:

  • 这会使页面进入一个永恒的循环刷新?
  • 创建函数以进行更改并在需要时执行它
  • 不,不工作。另一种选择是更改 URL:目前它有:/p/ 将其更改为 /product/ 我正在尝试删除一个 cookie,以便我可以运行相当大的 A/B 测试(_ff=v 是 cookie )
  • /p/ - 它的路径名 attr,如果你想改变它 - 使用 window.location.pathname
  • 你有代码示例吗?我不完全是 jQuery 或 JavaScript 的大师
【解决方案2】:

使用here 和here 提供的解决方案(稍作修改),您可以获取查询字符串值并更改它们。

从那开始,你可以使用下面的代码来做你需要的事情:

//This allows you to read the query string
(function($) {
    $.QueryString = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i)
        {
            var p=a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'))
})(jQuery);

(function(){
    //This allows you to set the query string parameters
    function updateQueryStringParameter(uri, key, value) {
        var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
        var separator = uri.indexOf('?') !== -1 ? "&" : "?";
        if (uri.match(re)) {
            return uri.replace(re, '$1' + key + ( (value !=  '' ) ? "=" + value : "") + '$2');
        }
        else {
            return uri + separator + key + ( (value !=  '' ) ? "=" + value : "");
        }
    }

    // When you load the page, you check if the query string doesn't contain "ffv"
    if(typeof $.QueryString["ffv"] == "undefined") {
        //If it doesn't, you add it
        window.location.href = updateQueryStringParameter(window.location.href,'ffv','');
    }
})();

你需要在添加之前检查ffv是否设置,以避免循环。

【讨论】:

    猜你喜欢
    • 2016-01-01
    • 2014-06-14
    • 1970-01-01
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2012-05-31
    • 1970-01-01
    相关资源
    最近更新 更多