Anil Namde
Anil Namde

Reputation: 6608

How to make JS execute in HTML response received using Ajax?

I have following workflow

  1. div on the page is used
  2. on users operation request is done to server side page whose html is retrived using ajax and dumped into the div
  3. With html markup some JavaScript is also dumped however that is not getting executed.

Why is so ? What could be the possible fix ?

Though i avoid doing things like this but in some old code implementations like these are very common.

Upvotes: 0

Views: 905

Answers (1)

Sean Kinsey
Sean Kinsey

Reputation: 38046

Scripts added using .innerHTML will not be executed, so you will have to handle this your self.

One easy way is to extract the scripts and execute them

 var response = "html\<script type=\"text/javascript\">alert(\"foo\");<\/script>html";
 var reScript = /\<script.*?>(.*)<\/script>/mg;
 response = response.replace(reScript, function(m,m1) {
     eval(m1); //will run alert("foo");
     return "";
 });
alert(response); // will alert "htmlhtml"

​ This will extract the scripts, execute them and replace them with "" in the original data.

Upvotes: 2

Related Questions