ajax innerHTML中js定义数组识别问题

最近写一个页面,需要在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

以上两篇文章给了我启发,在此致谢.

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值