javascript - 通过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
});
任何想法为什么这不起作用?
解决方案
您可以使用 localStorage 或 sessionStorage 来存储共享参数 beetwen 选项卡,并通过设置计时器以使用 setInterval 检查此参数来获取新更改的通知。
推荐阅读
- c# - 将明细表行转列linq转sql lambda表达式(主明细关系)
- python - 在 Stellargraph 中拆分用于 Node2vec 链路预测的训练测试集
- java - 如何在 jsqlparser 中验证 unpivot sql 查询?
- python - 不在 PyPI 中安装 repo
- c# - 如何最好地响应开放的 HTTP 范围请求
- xamarin.forms - 如何在 xamarin 表单中与从底部效果飞入并行制作多个控件的动画?
- mongodb - 如何在 MongoDB 中获取和使用字段名称列表?
- r - R中的S形曲线
- drupal - Drupal 8:提交表单后发送 PDF 文件
- server - 每 24 小时安排一次 python 执行