Bug Tracker

Modify

Ticket #2282 (closed bug: worksforme)

Opened 5 years ago

Last modified 15 months ago

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:
Blocking: Blocked by:

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

comment:1 Changed 5 years ago by davidserduke

  • Status changed from new to closed
  • Resolution set to worksforme

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.

Please follow the  bug reporting guidlines and use  jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.

View

Add a comment

Modify Ticket

Action
as closed
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.