简体   繁体   中英

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. 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() ?

You can use eval(String)

Or use new Function (String)

Or use 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.

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 )

Good luck

Yes, you can do that using eval .

However, remember eval is evil and it could potentially introduce security risks. Anyway, if you know what you're doing, that's the way to go

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