How to execute the scripts in AJAX response(HTML with scripts)


Send an ajax request and get the response as html. Scripts present in that response html are not executed automatically. We have to manually execute the script after getting the response. Two ways to do the same.

  • use eval command to execute the codes in script tag.
  • read the scripts in response and append into the HEAD tag.

In the above two methods, Sometimes the eval command could not work as expected. So i recommend the second one is the best. Also if the script codes getting longer its better to append all those scripts to head tag. Lets see how to execute the script in both the way.

invokeScript(contentId) – method for executing script separately.
scenario :  send a Ajax request, response is HTML with some scripts – scripts in response HTML should not loaded automatically.
to overcome this issue, we used this method to load the scripts separately.

Method 1 : using eval command.

function invokeScript(divid)
{
var obj= divid.getElementsByTagName(“SCRIPT”);
var len = obj.length;
for(var i=0; i<len; i++)
{
eval(obj[i].text);   // execute the scripts.
}
}

Method 2 : appending scripts to HEAD tag

function invokeScript(divid)
{
var scriptObj = divid.getElementsByTagName(“SCRIPT”);
var len = scriptObj.length;
for(var i=0; i<len; i++)
{
var scriptText = scriptObj[i].text;
var scriptFile = scriptObj[i].src
var scriptTag = document.createElement(“SCRIPT”);
if ((scriptFile != null) && (scriptFile != “”)){
scriptTag.src = scriptFile;
}
scriptTag.text = scriptText;
if (!document.getElementsByTagName(“HEAD”)[0]) {
document.createElement(“HEAD”).appendChild(scriptTag)
}
else {
document.getElementsByTagName(“HEAD”)[0].appendChild(scriptTag);
}
}
}

Ajax Basics – https://manikandanmv.wordpress.com/2008/09/23/ajax-asynchronous-javascript-and-xml/
Ajax GET request – https://manikandanmv.wordpress.com/2008/09/29/ajax-example/
Ajax POST request – https://manikandanmv.wordpress.com/2008/09/25/ajax-post-request/

Advertisements

Tags: , , , , , , , ,

3 Responses to “How to execute the scripts in AJAX response(HTML with scripts)”

  1. Suresh N Says:

    Hi, This blog is very helpful. Thanks, Suresh

  2. buraq Says:

    please give an example that use this script on the work.Thanx

  3. manikandanmv Says:

    Go here : https://manikandanmv.wordpress.com/2008/09/29/ajax-example/

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s


%d bloggers like this: