Google Closure Ajax Content
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.
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.
精彩评论