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

Question:
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.

Answer:
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.

Advertisements