Reputation: 1600
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()
?
Upvotes: 1
Views: 171
Reputation: 130
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
Upvotes: 2
Reputation: 28737
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
Upvotes: 0