正确的方法来执行JavaScript通过AJAX返回(无jQuery的) [英] Proper way to execute JavaScript returned via AJAX (no jQuery)
问题描述
说我得到了数据的AJAX负载请求,JavaScript和HTML,如混合的响应:
<脚本> window.alert(世界,你好!);< / SCRIPT>
&其中; P>这是一个段落。 Lorem存有悲坐阿梅德...< / P>
如果我只是把这种反应成 DIV
或其它容器,脚本不会被自动执行。我知道这可以通过的eval()
函数来完成(如下面的例子说明),但评估
是邪,所以我怎么能做到这一点是否正确? 注意:我不使用jQuery
下面是一个例如的AJAX的装载机的:
函数加载(ID,网址){
VAR阿贾克斯=新XMLHtt prequest();
ajax.onreadystatechange =功能(){
如果(ajax.readyState = 4!)返回;
VAR OBJ =的document.getElementById(id)的;
如果(OBJ!)回报;
obj.innerHTML = ajax.responseText;
//加载任何脚本
VAR S = obj.getElementsByTagName('脚本');
对于(VAR I = 0; I< s.length; ++ I)window.eval(S [I] .innerHTML); //< - 坏
}
ajax.open(GET,URL,真正的);
ajax.send(空);
}
请注意,您是从用户获取输入,并在脚本的网站上的上下文中运行它。因此,该脚本可以做任何事情在你的浏览器中运行的JavaScript /域将不得不这样做的能力(包括饼干偷,XSS,偷渡式恶意软件等)。
您可以切实做到降低风险的唯一的事情是不是的eval()用户提供的内容。我建议考虑以下方案:
- 使用的iframe来运行用户脚本环境: http://dean.edwards.name/weblog/2006/11/sandbox/一>
- 使用卡哈。它允许网站安全地嵌入第三方DHTML的Web应用程序,并能嵌入网页和嵌入式应用的丰富的互动。它使用了一个对象的能力的安全模型,以允许大范围的灵活的安全策略。 HTTP://$c$c.google.com/p/google-caja/
Say I get a response to a request for an AJAX load of data with a mix of JavaScript and HTML, e.g.:
<script>window.alert('Hello World!');</script>
<p>This is a paragraph. Lorem ipsum dolor sit amet...</p>
If I just place that response into a div
or other container, the script doesn't get executed automatically. I know this can be done via the eval()
function (as noted in the example below), but eval
is evil, so how can I do this properly? Note: I am not using jQuery.
The following is an example of the AJAX loader:
function Load(id,url){
var ajax=new XMLHttpRequest();
ajax.onreadystatechange=function(){
if(ajax.readyState!=4)return;
var obj=document.getElementById(id);
if(!obj)return;
obj.innerHTML=ajax.responseText;
// load any scripts
var s=obj.getElementsByTagName('script');
for(var i=0;i<s.length;++i)window.eval(s[i].innerHTML); // <-- bad
}
ajax.open("GET",url,true);
ajax.send(null);
}
Please note that you're taking input from the user and running it in the context of a script on your site. So the script can do anything that JavaScript running on your browser/domain would have the ability to do (including cookie stealing, XSS, drive-by malware, etc.).
The only thing you can realistically do to mitigate the risks is to not eval() user-provided content. I'd suggest to consider the following alternatives:
- Use iframe as an environment to run user's script: http://dean.edwards.name/weblog/2006/11/sandbox/
- Use Caja. It allows websites to safely embed DHTML web applications from third parties, and enables rich interaction between the embedding page and the embedded applications. It uses an object-capability security model to allow for a wide range of flexible security policies. http://code.google.com/p/google-caja/
这篇关于正确的方法来执行JavaScript通过AJAX返回(无jQuery的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!