Krann90
Krann90

Reputation: 1

html link variable

Is it possible to pass two variables through to another html page through a link?

For example... I have a directory page where when a user clicks a store link, it links to another html page with the map centered on the specific store. The function that centers the map on the store takes two variables, storeID, storeName. There are hundreds of stores and currently I would have to manually create each store page separately by hardcoding those two variables so that each page loads slightly differently. Is there a way to pass these two variables with a link, to avoid many different html pages?

Perhaps something along the lines of <a href "thisPage.html", var1, var2>?

ex. code

thispage.html

var1;
var2; 

function myFunc(var1, var2) {
    ~~~
}

Upvotes: 0

Views: 687

Answers (2)

sachleen
sachleen

Reputation: 31121

Not like that, but you can use URL parameters.

thisPage.html?var1=foo&var2=bar

Then you can read them on the second page. I like to use this function for that:

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

From http://www.netlobo.com/url_query_string_javascript.html

So on your second page, you can just do gup("var1") and you will get foo.

Upvotes: 1

Quentin
Quentin

Reputation: 943108

Use a query string.

In a URL a ? indicates the start of the query. It consists of a series of key=value pairs separated by & characters.

The encodeURIComponent function will escape text for inserting as a key or a value.

You can then assign it to the href attribute of the link element or set location.href to it.

Upvotes: 0

Related Questions