Reputation: 5762
I want to define functions and scripts in a database record then using Javascript convert the database field from a string to code.
I was thinking I could use 'eval', but this doesn't seem to work.
As an example:
var strTest = "function(strParams) { alert('hello: ' + strParams); };"
,fn = eval(strTest);
fn("World");
This doesn't work, eval returns undefined, hopefully this gives the idea of what I am trying to achieve.
Upvotes: 1
Views: 54
Reputation:
You could try something like this:
<script src="http://my-server/js-func/foobar.js"></script>
and have the server serve up the JS retrieved from the DB at that endpoint.
Upvotes: 0
Reputation: 288710
The problem is that eval
parses your function as a function declaration. But function declarations require a name.
Instead, you should make it a function expression, which doesn't require one.
var strTest = "(function(strParams) { alert('hello: ' + strParams); })";
eval(strTest)("World");
Only do this if you trust the string.
Alternatively, you may be interested in the Function
constructor:
var f = Function("strParams", "alert('hello: ' + strParams)");
f("World");
Upvotes: 3