I'm using ajax (with jQuery) to update parts of a webpage. The queries return html to insert at various places.
However, these html blocks sometimes contain javascript that write stuff where they're located. I mean, in some div of the html returned by AJAX, there's a script that gets included, and this script executes some document.write() instructions (typically scripts from our ads publisher we don't have any control over).
Now, if I just take the html returned by my AJAX queries and update the DOM with it, the javascript doesn't get executed.
What's the cleanest/easiest way to make sure that document.write() writes its stuff at the appropriate spots ?
-
1please share some code that you have tried so far.Bhushan Kawadkar– Bhushan Kawadkar2014年07月03日 05:33:07 +00:00Commented Jul 3, 2014 at 5:33
-
1Have a look Calling javascript returned from AJAX, may be it helps.Shubh– Shubh2014年07月03日 05:34:26 +00:00Commented Jul 3, 2014 at 5:34
-
May be you can take a look at Javascript's eval() function.Jyoti Puri– Jyoti Puri2014年07月03日 05:34:54 +00:00Commented Jul 3, 2014 at 5:34
2 Answers 2
You can't use document.write() with dynamically inserted content. The issue is that the current document has already been opened, parsed and closed upon the initial page load. If you now invoke document.write() from one of these scripts, it will clear the current document and start writing a new document. That will blank your browser window and write just the new content (which is certainly not what you want).
The options I can think of are:
Put the content in an iframe and load it via the
.srcattribute, not via ajax so the content can load into a new document anddocument.write()can do its normal, expected thing.Change those scripts to not use
document.write(). If you control that code, then the scripts need to be changed to insert content into a specific DOM element, not to try to write into the document stream because the document stream will not work the way you want once the original document has been parsed and the document closed.Hack
document.write()(by temporarily replacing it with a different method) so it captures thedocument.write()content in a different way while your dynamic content is being loaded and then you dynamically insert it into some existing DOM element rather than use the actualdocument.write(). This is truly a hack and it cannot be guaranteed that this will work in all browsers.
1 Comment
As you've no doubt discovered, document.write totally destroys the current document.
There are a few ways to handle it, the easiest one I've found is to replace document.write with a function that uses regular DOM manipulations.
document.write = function(str) {
var oldtxt = $("#destdiv").html();
oldtxt += str;
$("#destdiv").html(oldtxt);
}