Send and receive variable to another page

Asked

Viewed 4,925 times

3

I want to send a variable to another Javascript page, through the onclick button. I can send and see in the address bar its value. The problem is receiving on the second page. Example:

var object=3;

function btn_onclick() 
{
    window.location.href = "page.htm?object="+object;
}

<input type=button value=pass  onclick="return btn_onclick()" />

Page 2 to receive:

<script type="text/javascript">

   alert(object);

</script>
  • What is the type of variable you want to send? string, Object, integer?

2 answers

5


You need to get these variables from URL first. Answered this same question here, on your second page, you may have something like this:

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, " "));
}

And get the value of object thus:

var obj = getParameterByName('object');
alert(obj);

4

To receive you can use this simple function JavaScript that takes the URL and decodes it, storing the parameters within an array:

function urlDecode(string, overwrite){
	if(!string || !string.length){
		return {};
	}
	var obj = {};
	var pairs = string.split('&');
	var pair, name, value;
	var lsRegExp = /\+/g;
	for(var i = 0, len = pairs.length; i < len; i++){
		pair = pairs[i].split('=');
		name = unescape(pair[0]);
		value = unescape(pair[1]).replace(lsRegExp, " ");
		if(overwrite !== true){
			if(typeof obj[name] == "undefined"){
				obj[name] = value;
			}else if(typeof obj[name] == "string"){
				obj[name] = [obj[name]];
				obj[name].push(value);
			}else{
				obj[name].push(value);
			}
		}else{
			obj[name] = value;
		}
	}
	return obj;
}

var url = "www.testetestando.com?parametro1=oi&parametro2=x"; // Recebe a URL
var params = urlDecode(url.substring(url.indexOf("?")+1)); // Decodifica e monta um array com todos parametros
document.getElementById('teste').innerHTML = url+"<br/>"+params['parametro1']+"<br/>"+params['parametro2'];
<div id="teste"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.