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

后端 未结 7 1858
我在风中等你
我在风中等你 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).

提交回复
热议问题