Executing [removed] injected by innerHTML after AJAX call

前端 未结 11 1580
误落风尘
误落风尘 2020-11-22 05:02

There\'s a div called \"Content\":

It should be filled with data from a PHP file, by AJAX, including

相关标签:
11条回答
  • 2020-11-22 05:14

    This 'just works' for me using jQuery, provided you don't try to append a subset the XHR-returned HTML to the document. (See this bug report showing the problem with jQuery.)

    Here is an example showing it working:

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
    <html lang="en"> 
    <head> 
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
        <title>test_1.4</title> 
        <script type="text/javascript" charset="utf-8" src="jquery.1.4.2.js"></script> 
        <script type="text/javascript" charset="utf-8"> 
            var snippet = "<div><span id='a'>JS did not run<\/span><script type='text/javascript'>" +
            "$('#a').html('Hooray! JS ran!');" +
            "<\/script><\/div>";
            $(function(){
                $('#replaceable').replaceWith($(snippet));
            });
        </script> 
    </head> 
    <body> 
        <div id="replaceable">I'm going away.</div> 
    </body> 
    </html>
    

    Here is the equivalent of the above: http://jsfiddle.net/2CTLH/

    0 讨论(0)
  • 2020-11-22 05:17

    Here is the script that will evaluates all script tags in the text.

    function evalJSFromHtml(html) {
      var newElement = document.createElement('div');
      newElement.innerHTML = html;
    
      var scripts = newElement.getElementsByTagName("script");
      for (var i = 0; i < scripts.length; ++i) {
        var script = scripts[i];
        eval(script.innerHTML);
      }
    }
    

    Just call this function after you receive your HTML from server. Be warned: using eval can be dangerous.

    Demo: http://plnkr.co/edit/LA7OPkRfAtgOhwcAnLrl?p=preview

    0 讨论(0)
  • 2020-11-22 05:20

    My conclusion is HTML doesn't allows NESTED SCRIPT tags. If you are using javascript for injecting HTML code that include script tags inside is not going to work because the javascript goes in a script tag too. You can test it with the next code and you will be that it's not going to work. The use case is you are calling a service with AJAX or similar, you are getting HTML and you want to inject it in the HTML DOM straight forward. If the injected HTML code has inside SCRIPT tags is not going to work.

    <!DOCTYPE html><html lang="en"><head><meta charset="utf-8"></head><body></body><script>document.getElementsByTagName("body")[0].innerHTML = "<script>console.log('hi there')</script>\n<div>hello world</div>\n"</script></html>
    
    0 讨论(0)
  • 2020-11-22 05:22

    This worked for me by calling eval on each script content from ajax .done :

    $.ajax({}).done(function (data) {      
        $('div#content script').each(function (index, element) { eval(element.innerHTML); 
    })  
    

    Note: I didn't write parameters to $.ajax which you have to adjust according to your ajax.

    0 讨论(0)
  • 2020-11-22 05:22

    Another thing to do is to load the page with a script such as:

    <div id="content" onmouseover='myFunction();$(this).prop( 'onmouseover', null );'>
    <script type="text/javascript">
    function myFunction() {
      //do something
    }
    myFunction();
    </script>
    </div>
    

    This will load the page, then run the script and remove the event handler when the function has been run. This will not run immediately after an ajax load, but if you are waiting for the user to enter the div element, this will work just fine.

    PS. Requires Jquery

    0 讨论(0)
  • 2020-11-22 05:26

    If you load a script block within your div via Ajax like this:

    <div id="content">
        <script type="text/javascript">
        function myFunction() {
          //do something
        }
        myFunction();
        </script>
    </div>
    

    ... it simply updates the DOM of your page, myFunction() does not necessarily get called.

    You can use an Ajax callback method such as the one in jQuery's ajax() method to define what to execute when the request finishes.

    What you are doing is different from loading a page with JavaScript included in it from the get-go (which does get executed).

    An example of how to used the success callback and error callback after fetching some content:

      $.ajax({
        type: 'GET',
        url: 'response.php',
        timeout: 2000,
        success: function(data) {
          $("#content").html(data);
          myFunction();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert("error retrieving content");
        }
    

    Another quick and dirty way is to use eval() to execute any script code that you've inserted as DOM text if you don't want to use jQuery or other library.

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