Idrees Khan
Idrees Khan

Reputation: 7752

jQuery Loads .aspx Page But Doesn't Execute the Script Inside

i'm trying to load .aspx page using jquery like this;

        $('ul#menu li ul.collapse').on('click', 'li a', function (e) {
            e.preventDefault();
            var div = $('#content .container-fluid .row-fluid .span12');

            var url = $(this).attr('href');
            setTimeout(function () {
                var htmlPage = div.load(url + ' #MainContentHolder',
                    function () {
                         //other stuff
                    });
            }, 1000);

        });

However, my .aspx page does have javascript embedded like this;

<div id="MainContentHolder">
    <h1>Test Aspx Content</h1>
    <div>
        <script type="text/javascript">
            alert("hello");
        </script>
    </div>
</div

When, i see the resulted HTML, i can see the it is loaded (using firebug). But it's not showing the alert() message
I have also read all other questions on stackoverflow but it's not helpful on this to me;

UPDATE:

As suggested in asnwer, following code only works for the first time. I tried to turn off the cache:false and also tried from GET to POST;

 $.ajax({
         url:url,
         success:function(data){
         div.html(data);
    }
}); 

Upvotes: 0

Views: 1431

Answers (2)

Nilesh Thakkar
Nilesh Thakkar

Reputation: 2895

var htmlPage = div.load(url + ' #MainContentHolder', function () { //other stuff });

As per the documentation of .load(),

If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed.

Instead you may want to take your script in js file and use $.getScript(), which will load a JavaScript file from the server using a GET HTTP request, then execute it.

Edit:

Alternate way is to have only script in your page and load that page as shown in below link

jQuery .load() call doesn't execute javascript in loaded html file

OR

As already suggested use $.ajax() and in success callback function, you need explicitly execute your JS code as shown in this post. Use eval.

OR

You can load your dynamic page using .load and in success callback function use $.getScript as already suggested earlier.

I hope it helps!

Upvotes: 1

Khanh TO
Khanh TO

Reputation: 48972

$('ul#menu li ul.collapse').on('click', 'li a', function (e) {
            e.preventDefault();
            var div = $('#content .container-fluid .row-fluid .span12');

            var url = $(this).attr('href');
            setTimeout(function () {
                $.ajax({
                        url:url,
                        success:function(data){
                                    div.html(data);
                                    //other stuff
                                }
                        });  

            }, 1000);

        });

Upvotes: 1

Related Questions