简体   繁体   English

将JS变量传递到HTML文件

[英]Pass a JS Variable to a HTML file

I am constructing a Javascript variable in my code after some user interaction. 经过一些用户交互,我正在代码中构造一个Javascript变量。 I am trying to send that constructed JS object to another page. 我试图将构造的JS对象发送到另一页。

I am trying to send it via HREF using 我正在尝试使用HREF通过HREF发送

<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. 您不能像这样从javascript注入变量。

But you may pick up that anchor and manipulate its href attribute. 但是您可以选择该锚点并操纵其href属性。 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. PS:确保jsvariable的值是url编码的。

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: 将您的对象转换为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 在您的newpage.html上,阅读URL并提取所需的信息

     var jsParameter = ... 
  4. Convert JSON back to JS object: 将JSON转换回JS对象:

     var jsObject = JSON.parse(jsParameter); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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