Bug Tracker

Opened 12 years ago

Closed 12 years ago

Last modified 8 years ago

#2282 closed bug (worksforme)

script tags not evaluated in $.ajax

Reported by: emclain Owned by:
Priority: major Milestone: 1.2.3
Component: ajax Version: 1.2.2
Keywords: ajax, scripts, eval Cc:
Blocked by: Blocking:

Description

The documentation for $.ajax states that script tags are evaluated when doing an $.ajax call: http://docs.jquery.com/Ajax/jQuery.ajax#options

dataType:

"html": Returns HTML as plain text; included script tags are evaluated.

However, that doesn't seem to be the case. My test case is below. If the scripts were being executed, I would expect two alerts: the first "ajax" and the second "done". Instead I just see "done", both in FF2 and IE7.

I've also tried setting variables in the ajax page and reading them in the main page (in case there was some anomaly with alert()), but that didn't work either.

<!-- main page -->
Hello world.

<script src="/js/jquery-1.2.2.min.js"
        type="text/javascript"></script>

<script>
$(document).ready(function () {
    $.ajax({
        url: '/test_ajax.html',
        cache: false,
        dataType: 'html',
        success: function (data) {
            alert('done');
        },
    });
});

</script>
<!-- ajax page -->
<script>
alert('ajax');
</script> 

Change History (1)

comment:1 Changed 12 years ago by davidserduke

Resolution: worksforme
Status: newclosed

This is by design. As it says in the description the html is loaded as plain text. Unfortunately what it doesn't specify is that the scripts are evaluated when the plain text html is inserted in the DOM. I went ahead and updated the wiki text you indicated to make it more specific.

Again this is by design because often the script itself often manipulates parts of the loaded html. Of course those manipulations will fail unless it has first been inserted in the DOM. Try changing your success function to look like this:

  success: function (data) {
    $("head").append(data);
    alert('done');
  }

That should make it work how you are expecting. If there is still some bug I'm missing feel free to reopen this ticket.

Note: See TracTickets for help on using tickets.