将URL的一部分变量传递给脚本吗?

时间:2018-08-12 03:47:41

标签: javascript json variables 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中的变量传递给该页面上使用的脚本?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

布拉德(Brad)发布了一个链接,在上面可以找到答案。谢谢你,先生!这是给有兴趣的人的:

这是他链接到的页面: https://stackoverflow.com/a/3855394/362536

从那里,我发现以下代码已添加到脚本顶部,如下所示:

// get the variables

 var url_variable = (function(a) {
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; ++i)
    {
        var p=a[i].split('=', 2);
        if (p.length == 1)
            b[p[0]] = "";
        else
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return b;
})(window.location.search.substr(1).split('&'));

我的原始脚本中使用变量的部分如下:

{
    photo_set: url_variable["album"],
    tag: url_variable["tag"]
},

因此,如果我想要一张我最好的抽象照片的相册,我的网址将是: myphotosite.com/page.html?album=abstract&tag=best

它就像一种魅力!

相关问题