执行ajax返回代码中的脚本,支持document.write

来源:互联网 发布:linux telnet服务开启 编辑:程序博客网 时间:2024/05/21 08:39

来源:http://bluehua.org/2009/07/14/325.html/comment-page-1#comment-5409

有个产品要速度改版,改用ajax实现分页,可是页面中有很多内联脚本,求技术改比较慢,于是采用了最速都的方法:返回内容之后,把html塞到对应的层里,然后手动eval一下脚本。

这里有点小困难的就是脚本里面有document.write…。不过李宁叔叔说过…

demo:
支持返回代码中的内联或者外联的脚本
http://bluehua.org/demo/eval_inner_html/

原理是这样滴:
执行这些代码之前先把document.write改成自己的函数,用来收集输出的字符串

var _write = document.write;document.write = function( str ){    _inner_js.push( str );}
执行返回html中的脚本之后将document.write输出的代码添加到script标签的位置
var tmp = document.createDocumentFragment();appendHTML( tmp,  _inner_js.join( '' ) );s.parentNode.insertBefore( tmp, s );


0 0