Object.returnHTML and Javascript evaluation

One of my friends had a doubt and she had mailed me this.

In one of my pages, I am using ajax to show dynamic content. I am making an ajax call and using the innerHtml to show the content returned. The problem here is, my returned content has some javascript code which has to be executed. But its not. InnerHtml simply writes without executing any js. Is there any function which will execute the js in my content?

I replied to her and at the same time thought that it would be useful to my blog readers as well.

Unfortunately, No. While handling Ajax calls and assigning the returned content to returnHTML, the returned javascript does not get evaluated by default. You should explicitly evaluate it. And, how do you do that? Assign an id to your script tag and evaluate the javascript content within this script tag using eval() function.

For people, who think that this is complicated, there are some nice ajax libraries out there like prototype and script.aculo.us. You can use their functions and all you would need to do there is to set a boolean variable called evalScripts to true. Many popular sites like Digg and Tezaa use these libraries.

Let me know if this helped. If you found a better solution, let me know too.


5 thoughts on “Object.returnHTML and Javascript evaluation

  1. Wow! We can also use this:
    var scr = document.createElement(“script”);
    scr.text = “script”; // Script of Page

    Works fine!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s