0

我以前遇到过外部文件未运行的问题。

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

这是我需要运行的嵌入式 JavaScript,它通过正文的 .innerHTML 插入。目前它只是我页面中的“死代码”。请注意我作为 set 函数的第二个变量传入的 json。这是 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();
4

2 回答 2

1

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

于 2012-06-01T18:47:00.840 回答
0

另一种方式:为什么嵌入的 JavaScript 在响应 ajax 调用时不执行?

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

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

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

执行使用 .innerHTML 插入的 <script> 元素

于 2012-06-01T21:18:49.493 回答