Loading script tags via AJAX

前端 未结 4 543
渐次进展
渐次进展 2020-12-03 18:45

I have a div tag which is filled with script via an ajax call, but the script does not execute.

Is there a way to cause the script to execute?

相关标签:
4条回答
  • 2020-12-03 18:53

    If you set innerHtml of div, the script tags should execute. I am using $("#divid").load() to load dynamic contents and script tags do execute.

    Try using JQuery if it does not work out using plain javascript.

    0 讨论(0)
  • 2020-12-03 19:08

    I guess, you are writing script tag into innerHTML directly

    This will not work.

    document.body.innerHTML+="<script>alert(1)</scr"+"ipt>"; 
    

    you have to write using DOM functions like this

    var tag = document.createElement("script");
    tag.innerHTML="alert(1)";
    document.body.appendChild(tag); //can be append to any object other than body
    

    or Better use jQuery

    0 讨论(0)
  • 2020-12-03 19:10

    If you use jQuery's .html method it parses out the script tag and evals it:

    $("div").html('<script type="text/javascript">alert("This should work")</script>');
    

    If jQuery isn't an option you could write this yourself using either (1) a regular expression, or (2) parse out the DOM tree and find script tags. (#2 is how jQuery does it)

    0 讨论(0)
  • 2020-12-03 19:15

    It is always a good idea to separate content from code. Load content via AJAX and code by inserting <script> tags. If you are using jQuery, use $.getScript() to load scripts dynamically.

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