简体   繁体   中英

How do i pass a js variable from one html file to another?

My problem is pretty simple, but as i still lack proficiency in merging js,php and html, i couldn't find a solution for this problem. The problem involves 3 files:

JS1.js

function foobar(foo){
...
}

here foo is the same foo generated from HTML1.html file

HTML1.html

...<?php
$something = Object->method();
$array = Object->anotherMethod($something);
echo "<script type=\"text/javascript\"> 
            var foo =" . json_encode($array) . ";
     </script> ";
?>
...

here i generate the json_encode(d) version of my php array

HTML2.html

...<head>
<script type="text/JavaScript" src="js/JS1.js">
</head>
<body>
...
... onClick = \"foobar(foo)\">";
...
</body>

here, basically, i need it as the parameter to run my foobar js function in JS1.js file

So my question is, how do i pass foo from HTML1.html to HTML2.html ?

PS: obivously i have 2 splitted html files because i need them both and both do different things otherwise the problem would have never even occurred :) just to clear things up

In this case use a cookie : IN HTML1 , after setting var foo, set it in a cookie then get it from the HTML2

HELPER CODE (http://www.w3schools.com) in js :

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

and

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

theres 2 ways you could do it,

or

  • 2: [this is a very bad idea] have javascript add a value to the end of all links to pass the value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM