Manuel Lafond
Manuel Lafond

Reputation: 103

Executing javascript in ajax response

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 ?

Upvotes: 0

Views: 218

Answers (2)

jfriend00
jfriend00

Reputation: 707198

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:

  1. Put the content in an iframe and load it via the .src attribute, not via ajax so the content can load into a new document and document.write() can do its normal, expected thing.

  2. 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.

  3. Hack document.write() (by temporarily replacing it with a different method) so it captures the document.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 actual document.write(). This is truly a hack and it cannot be guaranteed that this will work in all browsers.

Upvotes: 2

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

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);
}

Upvotes: 1

Related Questions