简体   繁体   中英

Pass a JS Variable to a HTML file

I am constructing a Javascript variable in my code after some user interaction. I am trying to send that constructed JS object to another page.

I am trying to send it via HREF using

<a href="newpage.html?" + jsvariable">

But this one fails. Is there any other way to accomplish this ?

thanks

You cannot inject variables from javascript like that.

But you may pick up that anchor and manipulate its href attribute. There are many ways to do this.

Example:

... your html
<a id="someAnchor" href="newpage.html">test</a>

<script>
    document.getElementById("someAnchor").href += "?someParam=" + jsvariable;
</script>
... rest of your html

PS: Make sure the value of jsvariable is url-encoded.

Given that the data comes from user input, you'll want to make sure to protect against malicious inputs.

Try something like:

var anchorEl = // reference to your anchor.
anchorEl.href += '?data=' + encodeURI(jsvariable)

Note, the above solution works in cases where you want further user interaction to get to the next page. If you want to redirect the page directly, you can do:

window.location.href = 'newpage.html?data=' + encodeURI(jsvariable)

I haven't tested this but I think it will work:

  1. Convert your object to JSON:

     var jsonObject = JSON.stringify(jsvariable); 
  2. Then pass it into your url:

     <a href="newpage.html?" + jsonObject> 
  3. At your newpage.html, read the URL and extract the information that you need

     var jsParameter = ... 
  4. Convert JSON back to JS object:

     var jsObject = JSON.parse(jsParameter); 

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