Trying to select script tags from a jQuery ajax get response

后端 未结 3 1990
野性不改
野性不改 2020-12-06 04:55

I\'m on page A. A link is clicked, and I\'m loading in the DOM via jQuery get from page B. Inside page B\'s DOM are multiple dynamically-generated script tags with the class

相关标签:
3条回答
  • 2020-12-06 05:33

    jQuery doesn't actually append <script> elements to the DOM. Instead, it just evals the contents of the script. Since it isn't in the DOM, $(data).find(".dataScript") doesn't match anything.

    If you really need the contents of the <script> tag, you could try using a regular expression to parse the ajax response.

    Check out Karl Swedberg's comment for more info:

    All of jQuery's insertion methods use a domManip function internally to clean/process elements before and after they are inserted into the DOM. One of the things the domManip function does is pull out any script elements about to be inserted and run them through an "evalScript routine" rather than inject them with the rest of the DOM fragment. It inserts the scripts separately, evaluates them, and then removes them from the DOM.

    I believe that one of the reasons jQuery does this is to avoid "Permission Denied" errors that can occur in Internet Explorer when inserting scripts under certain circumstances. It also avoids repeatedly inserting/evaluating the same script (which could potentially cause problems) if it is within a containing element that you are inserting and then moving around the DOM.

    0 讨论(0)
  • 2020-12-06 05:37

    If you load the AJAX result like this:

    function (data) {
     // the result is loaded in the variable 'data'
    }
    

    And then push it into a div like this:

    function (data) {
     $("#someDiv").text(data);
    }
    

    The entire page including html tags will be placed as text so you can see the tags. You could trim the page to get only the scripts you want, but ask yourself is it is clever to do so.

    The thing is... if you just save the script as an external .js file you could load it in ajax as text :)

    0 讨论(0)
  • 2020-12-06 05:39

    The main issues are... expecting the <script> elements to be children of <div id='scripts'>, and using .find() instead of .filter().

    When using jQuery's $.get() and $.ajax(), the returned data is a text string. When you place data in a jQuery wrapper, $data = $(data), it's converted into an array: [p, div#scripts, div#divs, div#dataDiv, <script.dataScript>, <script.dataScript>]. Did you notice the <script> elements are no longer children of <div id='scripts'> but at the root? jQuery did that on purpose.

    $dataScripts = $data.filter('script.dataScripts') will give us a collection we can now iterate through like so:

    $dataScripts.each(function(i) {
        $('#scriptOutput').append($(this));
    });
    

    This will evaluate the scripts in $dataScripts, not insert them into the DOM like @Emmett mentioned.

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