首页 > 解决方案 > 将作为 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 中的变量传递给该页面上使用的脚本?

标签: javascriptjsonvariablesurl

解决方案


您可以使用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。


推荐阅读