How to execute javascript inside a script tag returned by an ajax response

后端 未结 7 1810
我在风中等你
我在风中等你 2020-11-30 05:10

I\'m sending a jquery get request like so:

$.get($(this).attr(\"href\"), $(this).serialize(), null, \"script\");

The response I expect to r

相关标签:
7条回答
  • 2020-11-30 05:29

    Jose Basilio's answer is okay, but I recommend replacing eval with jQuery's globalEval function...

    $.get($(this).attr("href"), $(this).serialize(), function(data) {
       script = $(data).text();
       $.globalEval(script);
    });
    

    globalEval is the function that would normally be called when you call an ajax method with a return type of script.

    This from the API documentation...

    This method behaves differently from using a normal JavaScript eval() in that it's executed within the global context (which is important for loading external scripts dynamically).

    0 讨论(0)
  • 2020-11-30 05:41

    I did this slightly differently, and used php land to make it easier. (I don't like using eval, nor do I like huge conspicuous rewrites).

    I placed all my jquery in a php string like so (there was a LOT more JavaScript in real life)

        $out .= "       $('#save_now').button(); \n";
        $out .= "       $('#save_now').click( function() {\n";
        $out .= "          return false;\n";
        $out .= "       }); \n";
    

    then also in php land

        echo "<script>\n";
        echo "  function onOpen(){ \n";
        echo $out;
        echo "  } \n";
        echo "</script>\n";
    

    then in the jQuery $.ajax call I do this

       $.ajax({
               url: geturl,
               type: 'post',
               data: getparams,
               success: function(data) {
                   mydiv.html(data);  
                   onOpen();  
               }, 
               cache: false
          });
    

    as you can see you don't nee the php land thing, it's just in my code base I did sort of need to do it. the trick is to do away with $(document).ready(function(){}); and roll your own

    0 讨论(0)
  • 2020-11-30 05:42

    You should be able to do the following:

    $.get($(this).attr("href"), $(this).serialize(), function(data){
       var script = $(data).text();
       eval(script);
    });
    
    0 讨论(0)
  • 2020-11-30 05:42

    Or:

    var myScript = new Function($('script#myscript',responseText).text());
    myScript();
    
    0 讨论(0)
  • 2020-11-30 05:49

    If I understand your question right, this should suffice to get the text out of the script tags:

    $(response).text()

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

    Say our response is in the 'response' var:

    script = response.replace(/<script>(.*)<\/script>/, "$1"); // Remove tags
    eval(script); // Execute javascript
    
    0 讨论(0)
提交回复
热议问题