最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

xmlhttprequest - How do I return eval(code) and get an object back with JavaScript? - Stack Overflow

programmeradmin0浏览0评论

I have this bit of code. What I want it to do is is load a .js file and then run it. wWen it runs I want it to return a parameter or even better an object.

This is the code in my page

var runCode = function(){
    var xhr=new XMLHttpRequest();
    xhr.open('GET','io.js',false);
    xhr.send();
    return eval(xhr.responseText);
};

And this is the is.js

var IO = new function(){
    this.run = true;
    return 'io';
};
return IO

But when I run it i get "Uncaught SyntaxError: Illegal return statement" in the console.

I have this bit of code. What I want it to do is is load a .js file and then run it. wWen it runs I want it to return a parameter or even better an object.

This is the code in my page

var runCode = function(){
    var xhr=new XMLHttpRequest();
    xhr.open('GET','io.js',false);
    xhr.send();
    return eval(xhr.responseText);
};

And this is the is.js

var IO = new function(){
    this.run = true;
    return 'io';
};
return IO

But when I run it i get "Uncaught SyntaxError: Illegal return statement" in the console.

Share Improve this question edited Sep 8, 2015 at 16:50 Jonathan Hall 79.8k19 gold badges159 silver badges203 bronze badges asked Oct 9, 2010 at 8:22 Tim P.Tim P. 4214 silver badges10 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

Another solution I found is to encapsulate your string to be eval'd inside a function, which is quite simple.

return eval("(function() {" + xhr.responseText + "})();");

You cannot use return outside of a function. But to return a value from eval you can use the following syntax-

eval('var IO = function(){this.run = true; return "io";};{IO};')

Problem is, you can't return outside of a function. What you'll need to is to return IO; from your runCode function after the request pletes.

Remove the new statement

var IO = function(){ 
    this.run = true; 
    return 'io'; 
}; 
return IO 
发布评论

评论列表(0)

  1. 暂无评论