views:

2068

answers:

5

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?

+1  A: 

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

$(response).text()

Kit
A: 

Say our response is in the 'response' var:

script = response.replace(/<script>(.*)<\/script>/, "$1"); // Remove tags
eval(script); // Execute javascript
cloudhead
If one were to use this solution, though, you'd probably have to complicate the regex a bit to allow for any attributes in the script tags, and probably anchor said regex to the beginning and end of the string. For example (totally untested): /^<script[^>]+>(.*)<\/script>$/
EvanK
You're right, using .text() is probably a better way anyway.
cloudhead
+1  A: 

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

Flavius Stef
That would work if the returned data was not wrapped in <script> tags
Jose Basilio
+8  A: 

You should be able to do the following:

$.get($(this).attr("href"), $(this).serialize(), function(data){
   script = $(data).text();
   eval(script);
});
Jose Basilio
Perfect. This did the trick. Thanks!!!
KJF
A: 

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

Alecoleti