javascript - 将作为 URL 一部分的变量传递给脚本?
问题描述
我的照片网站上的抽象摄影页面使用如下链接:
myphotosite.com/abstract.html
该页面使用脚本调用 Flickr API 来获取我的照片和信息。它包括如下几行:
{
photo_set: "abstract",
tags: "best"
},
我的网站目前有大量页面和大量脚本(每个照片集一个)。我想做的是在 url 中有一个页面加上变量和一个使用这些变量的脚本。按照上面的示例,链接将是这样的:
myphotosite.com/page.html?variable_1=abstract&variable_2=best
脚本将是这样的:
{
photo_set: "variable_1",
tag: "variable_2"
},
如何将 url 中的变量传递给该页面上使用的脚本?
解决方案
您可以使用URL API来解析页面的 URL 并从中提取查询参数。请参阅以下演示:
// Set this to window.location.href in actual code
let pageUrl = "https://myphotosite.com/abstract.html?variable_1=abstract&variable_2=best";
let url = new URL(pageUrl);
// Construct your object
let obj = {
photo_set: url.searchParams.get('variable_1'),
tag: url.searchParams.get('variable_2')
};
console.log(obj);
PS:Internet Explorer 不支持 URL API。
推荐阅读
- python - 按列分组后如何获取最高频率元素?
- .net - .net core - 工作单元通用存储库模式
- delphi - Delphi 属性编辑器,如 Delphi 中 TValueListEditor(或其他组件)处理的可折叠复合值
- python - Flask 包装器无法在发布请求上成功重定向
- javascript - React:何时将函数用作子函数以及何时使用组件
- laravel - thie laravel 安装宅基地,流浪失败
- katalon-studio - katalon 中的 utf-8 字符处理
- php - 如何为我的编码一起减小图像大小和调整图像大小?
- r - Shinyalert 响应问题
- javascript - 如何在数据网格的列标题和行中动态添加复选框?