Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - script tags in the HTML are parsed out by jQuery and not executed

I have an HTML page like so:

<html> <body> <div id='something'>     ...     <script>     var x = 'hello world';     </script>     ... </div> </body> </html> 

On another page, I am doing this:

$.ajax({     url: 'example.html',     type: 'GET',     success: function(data) {         $('#mydiv').html($(data).find('#something').html());         alert(x);     } }); 

jQuery, however, is not executing the javascript in the first file, even though the documentation says it does. How can I make it do that?

EDIT: Unfortunately in the real world application I am working on I don't have control over what the "included" page has. We are on the same domain, but I can't modify the code that it outputs as it is a packaged product our IT department will not let us modify.

like image 946
Jose Jose Avatar asked Apr 23 '10 14:04

Jose Jose


People also ask

How is jQuery executed?

The purpose of using jQuery is to make the javascript code easy to execute on the website, as jQuery wraps the many lines of code written in javascript, into a method that can be called with a single line of code. For this reason, a lot of common tasks that require javascript can be taken by jQuery.

Does jQuery go inside script tag?

We can include the jQuery CDN URL in the script tag and use jQuery in HTML. We can either write the jQuery in a separate . js file and include it in the HTML file or write the jQuery inside the script tag. First, go to the JQuery CDN website and choose the latest stable version of the jQuery.

What does jQuery HTML () do?

jQuery html() Method The html() method sets or returns the content (innerHTML) of the selected elements. When this method is used to return content, it returns the content of the FIRST matched element. When this method is used to set content, it overwrites the content of ALL matched elements.


1 Answers

As Pointy pointed out (excuse the pun), jQuery messes with the SCRIPT tags when you pass HTML to $(). It doesn't remove them though -- it simply adds them to the DOM collection produced from your HTML. You can execute the scripts like so:

$.ajax({     url: 'example.html',     type: 'GET',     success: function(data) {          var dom = $(data);          $('#mydiv').html(dom.find('#something').html());         dom.filter('script').each(function(){             $.globalEval(this.text || this.textContent || this.innerHTML || '');         });     } }); 
like image 198
James Avatar answered Sep 23 '22 02:09

James