Reputation: 23
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!
Upvotes: 1
Views: 388
Reputation: 488374
<script type="text/javascript">
function test() {
alert('i got loaded dynamically!');
}
</script>
$.get('file1.html', function(html) {
$(document).append(html);
test(); // alerts "i got loaded dynamically!"
});
Upvotes: 3
Reputation: 12052
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 :-)
Upvotes: 2
Reputation: 41222
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( );
});
Upvotes: 0
Reputation: 1866
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 ($).
Upvotes: 0
Reputation: 21630
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.
Upvotes: 0