最近写一个页面,需要在ajax返回的内容中插入一段js,这个段js主要是存储了一个js 数组.
ajax返回的内容被赋值给一个div 的innerHTML,本来以为主页面可以直接操作这个js数组了,结果发现完全不认这个数组.
查了一些资料以后发现在innerHTML中的js不会被执行,于是我参考一些资料把JS提取出来,然后eval.结果发现还是不行,虽然js代码执行了,但是数组在运行其他js函数时还是不被识别. 于是最终将这段js代码append到head里.终于可以被识别了.
以下是一些关键代码.
// the js in the ajax returned content will not be executed and recognized,
// so we get the js content and append it to the <head>
if(document.getElementById('jsArray'))
{
//get js content in the hidden span
innerScript=document.getElementById('jsArray').innerHTML;
//check to remove the script if it already exists
insertScript=document.getElementById("appendJs");
if(insertScript)
{
document.getElementsByTagName("head").item(0).removeChild(appendJs);
}
insertScript = document.createElement("script");
insertScript.type = "text/javascript";
insertScript.id = "appendJs";
insertScript.text=innerScript;
document.getElementsByTagName("head").item(0).appendChild(insertScript);
}
http://hi.baidu.com/rongrongmeimei123/blog/item/73773e153ed8fe4621a4e9f3.html
http://hi.baidu.com/shidadmt/blog/item/0ca268ce1e7d5735f9dc6107.html
以上两篇文章给了我启发,在此致谢.