开发者

How to run JavaScript code represented by a string?

Through AJAX I receive random string (built at RUNTIME on the server) that contain some JavaScript code like:

Plugins.add('test', function()
 { 
        return
            {
     开发者_C百科           html: '<div>test</div>',//EDITED
                width: 200
            }
 });//EDITED

In the client I want to be able to execute this code. I tried using eval function like this

eval("(" + str + ")");

but I get error. I removed all "\r\n" and removed the last ";"(semicolon) and after that eval function succeeded. But, If I add some comment to the code above, eval fails.

How I can run the code from the string?


Just remove those parenthesis:

eval(str);

asssuming that you made a typo in your question and your server is sending the missing end parenthesis and comma within the object:

Plugins.add('test', function()
 { 
        return {
                html: '<div>test</div>',  // <-- comma was missing
                width: 200
        };
 }
);   // <-- was missing

Note that eval() is considered "evil" as it is very dangerous.


new Function(str)()

or for JSON:

new Function('return ' + str)();

If it happens to fit your needs any better than eval. It's still evil like eval.


You are missing a comma in your object literal. Return on its own line will simply drop out of the function. I assume you want to return the object. You need to specify the return value on the same line.

Plugins.add('test', function() { 
   var ret =   {
                html: '<div>test</div>',
                width: 200,
            }     
   return ret

 };


You could return your string with a content type of "text/javascript" or "application/x-javascript" - the return value will be executed as JavaScript as soon as it is returned.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜