Send and receive variable to another page

3

I want to send a variable to another JavaScript page using 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>
    
asked by anonymous 12.03.2015 / 13:41

2 answers

5

You need to get these URL variables first. Answered this same question here , on your second page, you might get 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 like this:

var obj = getParameterByName('object');
alert(obj);
    
12.03.2015 / 13:53
4

In order to receive you can use this simple JavaScript function that takes the URL and decodes it, saving the parameters inside 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>
    
12.03.2015 / 14:01