eval的替代品,用于运行远程代码 [英] alternatives to eval for running remote code

查看:124
本文介绍了eval的替代品,用于运行远程代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有使用eval立即运行远程&的替代方法?受信任的javascript代码.

Are there any alternatives to using eval to immediatly run remote & trusted javascript code.

function load(filePath) {
    var o = $.ajax({
        url: filePath,
        dataType: 'html',
        async: false 
    }); 

    eval(o.responseText);
}

load("somePath");
// run a function that relies on the code from o.responseText being loaded
doSomethingWithCode();

我知道建议再次同步加载javascript.但是,如果没有选择,那么上面的eval可以使用任何跨浏览器的替代方法.

I'm aware that synchronous loading of javascript is adviced againts. But if there is no choice are there any cross browser alternatives for the use of eval above.

要更详细地说明正在加载的代码是一个自执行函数.哪个需要在doSomethingWidthCode之前执行.它也是从同一域的服务器上加载的,因此值得信赖.

To clarify in more detail the code being loaded is a self executing function. Which needs to execute before doSomethingWidthCode. It's also being loaded from the server on the same domain hence its trusted.

推荐答案

动态脚本文本插入是eval的唯一替代方法.

Dynamic script text insertion is the only alternative to eval.

var head    = document.getElementsByTagName('head')[0] || document.documentElement,
    nscr    = document.createElement('script');

    nscr.type           = 'text/javascript';
    nscr.textContent    = o.responseText;
    nscr.setAttribute('name', 'dynamically inserted');
    nscr.onload         = nscr.onreadystatechange = function() {
              if( nscr.readyState ) {
                   if( nscr.readyState === 'complete' || scr.readyState === 'loaded' ) {
                      nscr.onreadystatechange = null;
                       doSomethingWithCode();
              }
              else {
                  doSomethingWithCode();
              }
    };

    head.insertBefore(nscr, head.firstChild);

仅需提一下:textContent在InternetExplorers中不可用.您可能需要在其中使用.text,因此对其进行少量检测即可使其跨浏览器兼容.

Only thing to mention: textContent is not available in InternetExplorers. You would need to use .text instead there, so a little detection for that makes it cross-browser compatible.

修改

要使syncronous加载动态脚本标签,可以添加nscr.async = true;.无论如何,这仅适用于最先进的浏览器.

To have a syncronous loading dynamic script tag, you could add nscr.async = true;. Anyway, this only works in cutting edge browsers.

这篇关于eval的替代品,用于运行远程代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆