Google 关闭 Ajax 内容

发布于 2024-11-17 17:54:43 字数 283 浏览 1 评论 0原文

如何在 DIV 中显示 XHR responseText 的 HTML 内容并删除其

类似 Prototype JS 中的 extractScripts

How can I display the HTML content of a XHR responseText in a DIV and strip out its <script> tags and append them to the head tag? (using Google Closure)

Something like extractScripts in Prototype JS.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

や三分注定 2024-11-24 17:54:43

如果responseText是一个带有HTML和脚本标签的整个网页,那么也许您应该将其附加到iFrame和iFrame src,并让浏览器为您管理所有内容,而不是将其放在您必须管理的DIV中网页的不同部分。

如果您确实想获取responseText并将其直接放入您自己文档中的div中,那么您有几个选择。

首先,如果响应只是一个嵌入脚本标签的 HTML 片段(不是整个网页),那么您可以将整个响应读取到 JS 变量中,然后将其分配给 DIV 的 .innerHTML 属性。浏览器将解析 HTML,包括嵌入的标签,并对其进行评估,就好像它最初是该 div 的一部分一样(除非脚本执行时间显然要等到您分配 .innerHTML 之后才执行。

举个例子:

var myDiv = document.getElementById("myDiv");
myDiv.innerHTML = responseText;

其次,如果有出于某种原因你想单独取出标签(我想不出这样的原因与第一个选项相比),那么你必须自己从responseText中解析开始和结束脚本标签,放入JS代码将它们之间的文本放入 JS 变量中并在该变量上使用 eval 来执行它并使其成为文档的一部分,然后将剩余的 HTML 分配给 div 的 innerHTML 属性,如上面的示例所示,

如果该脚本中有 document.write ,则该脚本将不起作用。第二种方式是因为 document.write 没有位置上下文。如果这些脚本标记依赖于任何页面加载方法(例如 onload),那么脚本也不会看到这些事件(除非它是 iFrame 的 src)。

If the responseText is a whole web page with HTML and script tags, then maybe you should just attach it to an iFrame and the iFrame src and let the browser manage it all for you rather than put it in a DIV where you have to manage the different parts of the web page.

If you really want to get the responseText and put it directly into a div in your own document, then you have a couple options.

First, if the response is just an HTML fragment with embedded script tags (not a whole web page), then you can just read the whole response into a JS variable and then assign it to the .innerHTML attribute of your DIV. The browser will parse the HTML, including the embedded tags and evaluate it as if it was originally part of that div (except the script execution timing obviously isn't until right after you assign the .innerHTML.

As an example:

var myDiv = document.getElementById("myDiv");
myDiv.innerHTML = responseText;

Second, if there's some reason you want to pull out the tags separately (and I can't think of such a reason versus the first option), then you'll have to parse the start and end script tags out of the responseText yourself, put the JS code text in between them into a JS variable and use eval on that variable to execute it and make it part of your document. Then, assign the remaining HTML to the innerHTML attribute of your div as in the example above.

If that script has document.write in it, that won't work this second way because there's no location context for the document.write. If those script tags rely on any page loading methods like onload, then the scripts also won't see those events (except if it's the src of an iFrame.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文