Pass a variable that's part of a URL to a script?
Clash Royale CLAN TAG#URR8PPP
Pass a variable that's part of a URL to a script?
The page for abstract photography on my photo site uses a link like this:
myphotosite.com/abstract.html
That page uses a script to call on the Flickr API to fetch my photos & info. It includes a few lines like this:
photo_set: "abstract",
tags: "best"
,
My site currently has a ton of pages and a ton of scripts (one of each for each photo set). What I'd like to do is have one page plus variables in the url and one script which uses the variables. Following the example above, the link would be something like this:
myphotosite.com/page.html?variable_1=abstract&variable_2=best
And the script would be something like this:
photo_set: "variable_1",
tag: "variable_2"
,
How do I pass variables in a url on to a script used on that page?
Thanks, Brad! You led me to the answer, which I posted in full below.
– 2oh1
Aug 15 at 18:32
2 Answers
2
You may use the URL API to parse the page's URL and extract the query params from it. See the following demo:
// 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: URL API is not supported on Internet Explorer.
Brad posted a link above which led to the answer. Thank you, sir! Here it is for anyone who is interested:
Here's the page he linked to:
https://stackoverflow.com/a/3855394/362536
From there, I found the following code which I added at the top of my script, as follows:
// 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('&'));
The part of my original script for using the variables is as follows:
photo_set: url_variable["album"],
tag: url_variable["tag"]
,
Thus, if I want an album of my best abstract photos, my url would be:
myphotosite.com/page.html?album=abstract&tag=best
It works like a charm!
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
stackoverflow.com/a/3855394/362536
– Brad
Aug 12 at 3:53