如何在.innerHTML写入中运行嵌入式JavaScript?

时间:2012-06-01 18:43:23

标签: javascript json

我以前遇到过这个问题,外部文件没有运行。

我通过动态加载文件来解决这个问题......即。在JavaScript中创建元素并通过.src属性链接到它(这样做而不是在html中使用脚本标记)。我需要在这里做类似的事吗?

这是我需要运行的嵌入式JavaScript,它通过正文的.innerHTML插入。目前它只是我页面中的“死代码”。注意我将json作为第二个变量传入set函数。这是PHP编写并通过ajax POST传递给客户端。

<script type='text/javascript'>new Arc.Shared().set( 'tweet_data', [{"id":"1","0":"1","picture":"0","1":"0","name":"Test Account","2":"Test Account","tweet":"Hi","3":"Hi","time":"1338559048","4":"1338559048"},{"id":"1","0":"1","picture":"0","1":"0","name":"Test Account","2":"Test Account","tweet":"hi","3":"hi","time":"1338558809","4":"1338558809"},{"id":"1","0":"1","picture":"0","1":"0","name":"Test Account","2":"Test Account","tweet":"<a class=\"bookmark_tweet\" target=\"_blank\" href=\"http:\/\/ebay.com\">ebay <\/a>","3":"<a class=\"bookmark_tweet\" target=\"_blank\" href=\"http:\/\/ebay.com\">ebay <\/a>","time":"1338504456","4":"1338504456"},{"id":"1","0":"1","picture":"0","1":"0","name":"Test Account","2":"Test Account","tweet":"foo","3":"foo","time":"1338504225","4":"1338504225"},{"id":"1","0":"1","picture":"0","1":"0","name":"Test Account","2":"Test Account","tweet":"foo","3":"foo","time":"1338504222","4":"1338504222"},{"id":"1","0":"1","picture":"0","1":"0","name":"Test Account","2":"Test Account","tweet":"foo","3":"foo","time":"1338504220","4":"1338504220"},{"id":"1","0":"1","picture":"0","1":"0","name":"Test Account","2":"Test Account","tweet":"foo","3":"foo","time":"1338504217","4":"1338504217"}] );</script>

备注:

Eval Snippet的替代方案:

var myCode = 'alert("Howdy?");';
 var myFucn = new Function(myCode);
 myFucn();

2 个答案:

答案 0 :(得分:1)

如果你想运行AJAX注入的JS,你应该在其上调用“eval()”(出于安全原因)。另一种可能性是通过<script src='[url to your JS]'></script>标记加载它。

答案 1 :(得分:0)

Why doesn't embedded JavaScript execute when inserted in response to an ajax call?

的另一种方式

这是append子方法...,它采用ajax responseText并将其附加到DOM中。

function onSuccess() {
    src = document.createElement('script');
    src.innerHTML = this.responseText;
    document.body.appendChild(src);
}

第三种方法是让外部元素在这里触发它:

Executing <script> elements inserted with .innerHTML