Al wrote:

Hello,

I'm having an issue with getting embedded javascript code to actually
run when loaded via an Ajax.Request() call and the callback function
inserts the generated HTML and js code to my current page.  It seems
that the javascript code is not properly parsing.
I had a similar problem in the system I am writing.

I found that prototype.js has an evalScripts extention to the String object. Calling this will execute code at run time. The one problem with this is that any code that defines functions works only while being evaluated. The functions are not defined if you try to call them later.

If you need to add additional functions to an existing page you need to add a script element to the DOM and get it evaluated.

After a little experimenting I finally came up with this function:

function loadScripts(scrId, scrCode)
{
  if(document.getElementById(scrId) == null)
  {
    var head  = document.getElementsByTagName("head").item(0);
    scrHandle = document.createElement("script");
    scrHandle.id = scrId;
    scrHandle.type = 'text/javascript';
    void(head.appendChild(scrHandle));
  }
  scrHandle.text = scrCode;
}


This basically just adds a new script element to the DOM and
then loads and evaluates a string containing javascript at run time. Any functions that are defined in the loaded string will be available and callable from that point onward.

The scrId is a unique name used to identify the new script
element, and the scrCode is the actual script text to load.

This function works on Firefox 1.x, IE 6.x and Opera 8.x that I have
tried.

Hope this helps,

-- Will Merrell



_______________________________________________
Rails-spinoffs mailing list
Rails-spinoffs@lists.rubyonrails.org
http://lists.rubyonrails.org/mailman/listinfo/rails-spinoffs

Reply via email to