pe**********@gmail.com said the following on 9/6/2006 4:41 AM:
Hi,
My AJAX response is a bit of HTML that I insert into the DOM. I extract
the contents of the script elements in the response into an array
called aScripts. I then want to append these to an element so that the
scripts will actually execute. I am trying a variation on what Randy
Webb posted a few months ago.
function insertScripts(element, aScripts) {
if(typeof element == "string") {element =
document.getElementById(element);}
for (var i=0, t=aScripts.length; i<t; i++) {
var newScript = document.createElement('script');
newScript.type = "text/javascript";
newScript.text = aScripts[i];
element.appendChild(newScript);
//newScript.appendChild(document.createTextNode(aScr ipts[i]));
//eval(aScripts[i]);
}
};
If I uncomment the eval() line then the scripts actually do execute but
using eval() defeats the purpose of Randy's suggested solution. It
seems like the "text" property is non-standard.
The problem isn't the "text" property. It is directly related to your
parameter name of "aScripts"
Any way to rescue this bit of code?
aScripts = new Array()
aScripts[0] = "alert('hi with tags')"
aScripts[1] = '<script type="text/javascript">alert(\'hi with
tags\')<\/script>'
function insertScripts(element) {
if(typeof element == "string")
{element =document.getElementById(element);}
for (var i=0,t=aScripts.length; i<t; i++) {
var newScript = document.createElement('script');
newScript.type = "text/javascript";
newScript.text = aScripts[i];
element.appendChild(newScript);
}
};
Calling that code as such:
insertScripts('scriptsDiv')
Does the same thing in IE7, Mozilla and Opera 9. I get the first alert,
I don't get the second one. IE throws a Syntax Error, Opera 9 Javascript
Console shows an error and points at the <script tag in the entry. So,
if your script snippet has a script tag still in it, it won't execute.
Mozilla totally dropped the ball on this one. It doesn't throw an error
(no messages in the console), it simply doesn't do *anything* after the
first alert.
Adding the eval call back in didn't change any of the behavior and that
leads to the passing of the array name. alert(t) and you will find that
it alerts 8 which is the length of the string "aScripts" and that is the
source of your problems. If you stop passing it as a parameter, it
remains the name of an Array. If you pass it as a parameter, then it's
not an Array unless you pass a reference to an Array but you said that
aScripts was the name of your Array.
--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ -
http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices -
http://www.JavascriptToolbox.com/bestpractices/