ajax loaded content, script is not executing

后端 未结 2 1329
既然无缘
既然无缘 2020-12-11 06:57

I am using jquery address plugin for loading pages, but without hash(#).

index.html:

Link
相关标签:
2条回答
  • 2020-12-11 07:38

    I've encountered a case when an ajax call would return new HTML that includes the script that needs to execute. The code looked like this:

    $.ajax('/url', {
      method: 'get',
      success: function(response) {
        document.getElementById("my-body").innerHTML = response;
      }
    });
    

    In that code above, response would contain the script that needs to be executed, but it would not execute. Changing the success callback to the following fixed it:

    $("#my-body").html(response);
    

    I'm not sure why that was the case (obviously it has to do with the implementation of .html() method). Perhaps someone could comment with an explanation

    0 讨论(0)
  • 2020-12-11 07:43

    document.ready happens only once, when document is loaded. AJAX request does not cause it.

    <div id="content">
        <p>text</p>
        <script type="text/javascript">
                alert('loaded');
        </script>
    </div>
    

    This should work. Also try to change $(msg).find("#content").html() to $(msg).find("#content")[0].innerHTML, as jquery html strips out tags.

    EDIT

    Take a look at this thread there is a long discussion about why that happens. In case like this $(msg) jquery will always remove script tags. But at the same time $(msg).filter("script") returns scripts, so you can find those scripts first and then insert them all after $('#content').html( $(msg).find("#content").html() );

    0 讨论(0)
提交回复
热议问题