首页 > 解决方案 > 通过ajax在另一个页面上触发功能

问题描述

在我们的网站上,我们正在从第三方加载一个 IIFE 脚本,该脚本检查某个 url 参数并设置一个 cookie。在另一个页面上,我想设置该参数而不重定向用户、重新加载页面或篡改第三方代码。

我想这样做的原因是因为第三方仅从 url 参数设置数据,通常用户通过社交媒体或其他地方的链接导航到该站点,并且该参数是预定义的(即:example.com/?color =红色)。但是,我们希望客户能够选择由第三方代码设置的参数。我想出的一个可能的解决方案是通过 ajax $.get 请求,但这不起作用。

为了更好地了解我在这里要完成的工作,简化了整个过程:

在 example.com

(function(){

function run_this(){
    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    const fav_color = urlParams.get('color');
    document.cookie = 'customer_fav_color=testing that we can set colors through a GET request - customer color is '+ fav_color;
}


run_this();
})();

在 example.com/cart

 var fav_color = 'blue';
    var color_xhr = $.get('https://example.com',{color: fav_color}
         ).done(function(data, status, xhr){
              // do something here
         });

任何想法为什么这不起作用?

标签: javascriptjqueryhttp

解决方案


您可以使用 localStorage 或 sessionStorage 来存储共享参数 beetwen 选项卡,并通过设置计时器以使用 setInterval 检查此参数来获取新更改的通知。


推荐阅读