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

I'm sending a jquery get request like so:

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

The response I expect to receive will be wrapped in script tags.

I understand the browser doesn't execute the response unless its returned without the script tags. Normally I would remove the tags from the response but in this situation I don't have access to the code running on the remote machine so cannot strip out the tags at the source.

Is there a way I can strip out the script tags from the response client side and execute the javascript?


Solution 1:

You should be able to do the following:

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

Solution 2:

Or:

var myScript = new Function($('script#myscript',responseText).text());
myScript();

Solution 3:

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

$(response).text()

Solution 4:

Would this help you: http://docs.jquery.com/Ajax/jQuery.getScript ?

Solution 5:

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).