acl77
acl77

Reputation: 341

using 'location.href' to pass variable

I've found several posts alluding to the location.href method. But I can't find anything about how to use the variable on the next page that's opened.

I have a function with a single line of code in an external js file:

function nextPage()
{location.href='page2.html?foo=' + src;}

It's activated by a button in the html file. How do I use this on the next page that's opened? I'm assuming this makes 'foo' available. ('src' is an integer stored as a global variable in the external js file. It's just a number between 1 and 5).

Upvotes: 0

Views: 532

Answers (2)

Sridhar R
Sridhar R

Reputation: 20408

On the next page you can get the value using:

http://page2.html?foo=

location.search
> ?foo=
location.search.substring(1)
> foo=

In Script Tag You Put

 var array=location.search;
var data = array.split("foo=");
var divid=data[1];//It has your foo value

Upvotes: 1

Sohil Desai
Sohil Desai

Reputation: 2988

if you are using javascript then try this code to get querystring value

function getParameterByName(name) 
{
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

var value = getParameterByName('foo');

Upvotes: 0

Related Questions