简体   繁体   中英

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); } }); 

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!

$('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);

        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM