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/
Tags: AJAX, ajax basics, ajax example, ajax GET request, AJAX POST request, AJAX response HTML with scripts, append scripts to HEAD tag, eval, execute scripts in AJAX response
November 14, 2008 at 7:51 pm |
Hi, This blog is very helpful. Thanks, Suresh
May 16, 2009 at 6:54 am |
please give an example that use this script on the work.Thanx
May 16, 2009 at 1:03 pm |
Go here : https://manikandanmv.wordpress.com/2008/09/29/ajax-example/