jQuery: Evaluate script in ajax response

前端 未结 4 985
南笙
南笙 2020-11-30 15:13

XML responses from my webapp have both HTML to add to the page AND some have a script to run.

I\'m trying to send back XML from my webapp like:



        
相关标签:
4条回答
  • 2020-11-30 15:40

    This is the best answer that i found. Work perfect:


    element.innerHTML = xmlhttp.responseText;
    var scriptElements = element.getElementsByTagName('SCRIPT');
    for (i = 0; i < scriptElements.length; i ++) {
        var scriptElement = document.createElement('SCRIPT');
        scriptElement.type = 'text/javascript';
        if (!scriptElements[i].src) {
            scriptElement.innerHTML = scriptElements[i].innerHTML;
        } else {
            scriptElement.src = scriptElements[i].src;
        }
        document.head.appendChild(scriptElement);
    }
    

    Thanks to Joseph the Dreamer. Original answer here.

    EDIT:

    Clarification:

    1. scripts only run inside script tag
    2. added scripts after document load, only take effect if it is added to the head tag

    Thanks to Deniz Porsuk for the comment to improve the answer

    0 讨论(0)
  • 2020-11-30 15:49

    JSON would be better suited for this purpose than XML imho.

    0 讨论(0)
  • 2020-11-30 15:53

    You'd rather send JSON, it's way easier to interpret. Example:

    // Suppose your response is a string:
    // { html: "<p>add me to the page</p>, script:"alert('execute me');" }
    var obj = eval( "(" + response + ")" ) ;
    eval( obj.script ) ;
    
    0 讨论(0)
  • 2020-11-30 15:56

    You can use the jQuery library to make the XML request to your backend and also parse it

    $(document).ready(function()
    {
      $.ajax({
        type: "GET",
        url: "your/url/that/returns/xml",
        dataType: "xml",
        success: function (xml) {
          // xml contains the returned xml from the backend
    
          $("body").append($(xml).find("html-to-insert").eq(0));
          eval($(xml).find("script").text());
        }
      });
    });
    

    You can find out more about jQuery here and here

    I haven't tested it, but it should work according to this article.

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