简体   繁体   English

从……执行自包含的javascript

[英]Executing self-contained javascript from… javascript

I have javascript that is being generated at design time that needs to be executed to find a value at run time. 我有在设计时生成的javascript,需要在运行时执行该javascript来查找值。 The code is stored as a string in an object and I would like to be able to execute it and retrieve the value and then scrap the code. 代码以字符串形式存储在对象中,我希望能够执行它并检索值,然后取消代码。 Is there a way to do this? 有没有办法做到这一点? Do I have to use eval() ? 我必须使用eval()吗?

You can use eval(String) 您可以使用eval(String)

Or use new Function (String) 或使用new Function (String)

Or use document.createElement 或使用document.createElement

[edited] [编辑]

Depend on how it was done your code 取决于代码的处理方式

1 - if those strings are saved in shared across different pages (with cookies or database ), then SERVER-SIDE you can generate a tag <script> with the values ​​saved in a JSON for quick access. 1-如果这些字符串在不同页面上共享保存(使用cookiesdatabase ),那么SERVER-SIDE可以生成一个标记<script> ,其值保存在JSON以便快速访问。

2 - If the strings are saved only at runtime (ie in pagination are not recoverable values) you may not need to save these values ​​in Strings , talves you can create a global Json in Window Object (eg. window.MyObjectGlobal) , making the values ​​accessible at any time on the page (since there is no paging) - is idea can also be reused in case of using the SERVER-SIDE , combined with Ajax (ajax only to save the data in your database), or document.cookie (but will have to use document.createElement("script") or eval ) 2-如果仅在运行时保存字符串(即在分页中不是可恢复的值),则可能不需要将这些值保存在Strings ,可以在Window Object (eg. window.MyObjectGlobal)创建global Json Window Object (eg. window.MyObjectGlobal) ,使值可以在页面上的任何时候访问(因为没有分页)-如果将SERVER-SIDEAjax结合使用(也可以将ajax用于将数据保存在数据库中),也可以重用该想法;或document.cookie (但必须使用document.createElement("script")eval

Good luck 祝好运

Yes, you can do that using eval . 是的,您可以使用eval做到这一点。

However, remember eval is evil and it could potentially introduce security risks. 但是,请记住, eval是邪恶的,它可能会带来安全风险。 Anyway, if you know what you're doing, that's the way to go 无论如何,如果您知道自己在做什么,那就是要走的路

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

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