为什么不嵌入时响应Ajax调用插入的JavaScript执行?Ajax、JavaScript

2023-09-10 15:48:28 作者:╰ゝ蝴蝶为花醉

插入JavaScript中的.innerHTML不会导致它运行。

Inserting JavaScript in the .innerHTML does not cause it to run.

我有我称之为的Mini-Feed中,用户提交一个职位。这将启动一个Ajax调用,用户数据保存到mysql表。从那里PHP生成的XHTML。从那里的PHP生成的XHTML发送回JavaScript作为响应文本。这XHTML包含嵌入用来显示pretty的时间的JavaScript。

I have what I call a mini-feed in which a user submits a post. This initiates an ajax call which saves the user data to the mysql table. From there PHP generates the xhtml. From there the the PHP generated xhtml is sent back to javascript as response text. This xhtml contains embedded javascript used to display "pretty time".

现在,如果PHP generatd XHTML / JavaScript是发送到客户端在此工作的一个非Ajax方法。但是,当我把它的responseText,然后使用.innerHTML它不能正常更新DOM。似乎不管什么机制,拿起javacript与在XHTML不喜欢写进封闭div标签的.innerHTML属性嵌入的JavaScript。

Now if the PHP generatd xhtml/javascript is send to the client in a non-ajax way this works. But when I send it as responseText and then update the DOM using .innerHTML it does not function. Whatever mechanism that picks up javacript with in the XHTML does not seem to like the embedded javascript written into the .innerHTML property of the enclosing div tag.

有一个容易解决的呢?还是我来构建用户界面与使用了JavaScript的只是插入这一切为的innerHTML ...在previous后有人提到,.innerHTML是不是好的做法。或许,这就是他们的意思。

Is there an easy fix for this? Or do I have to construct the UI with in the javascript with out just inserting it all in as innerHTML...in a previous post someone mentioned that .innerHTML was not good practice. Perhaps this is what they meant.

推荐答案

以下code应该工作:

The following code should work:

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

不过,我将与cwallenpoole同意,为什么不把所有的JavaScript code(为pretty的-fying日)是已经写在先进的主页? (或脚本包含什么的)。

But I would agree with cwallenpoole that why not have all that javascript code (for pretty-fying the date) be already written in advanced in the main page? (or script included or something).