views:

195

answers:

7

Does anybody know how to execute javascript functions in an html that is loaded via ajax? I mean the html contains both plain text and javascript. In my case it seems that only the in-line javascript (eg. onclick="dosomething();return false") gets executed. The pre-defined functions which are wrapped by < script language = "javascript >are unfortunately ignored..

i have search couple articles through the site but the results are either use getScript to load a pure js or use eval. please help me out of this! Thank you very much!

A: 

Look up jquery event delegation, and the .live() method.

http://docs.jquery.com/Events/live#typefn

Event delegation is especially useful and efficient if you're working with a large piece of html that you've added dynamically.

ScottE
A: 

Ohoh thanks ! but it does not addresses the ajax problem..

Jing
A: 

I don't know if this fixes your problem... but if your loaded html also includes a link to jquery's code base, it can cause issues with the child-code not correctly linking with the handle to the jquery object ($).

Ape-inago
A: 

If I understand you correctly, you receive from your AJAX call plain HTML mixed with javascript code, e.g. with tags. I'm didn't checked it, but you can try to do the following:

$.get( ajaxURL, function( data)
{
   $( "head").append( $( data).find( "script"));
   yourFunctionCall( );
});
Artem Barger
+2  A: 

According to the doco, if you use $.ajax and specify a data type of "html", included script tags are evaluated when inserted in the DOM. Make sure your server is returning the correct data type, see Specifying the Data Type for AJAX requests for more info

If that doesn't help, Artem's approach also works well, providing you only make the request once. If you are making the same $.get call over and over, you'll end up with multiple copies of yourFunctionCall in the head, and Strange Things will happen :-)

Dan F
+2  A: 

File 1:

<script type="text/javascript">
function test() {
  alert('i got loaded dynamically!');
}
</script>

File 2:

$.get('file1.html', function(html) {
  $(document).append(html);
  test(); // alerts "i got loaded dynamically!"
});

See it in action.

Paolo Bergantino
+1  A: 

Thank you all!! i think that would be it! thanks alot!

sorry guys i can't vote up since my reputation is below 15..i just registered...

Jing
You should be still able to mark one of the answers as accepted.
Rene Saarsoo
And here's a bit of rep to get you started :)
Rene Saarsoo