Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 414
KJF Avatar asked Jun 10 '09 20:06

KJF


People also ask

How do I run a script tag in JavaScript?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

How do I return a response from Ajax?

What you need to do is pass a callback function to the somefunction as a parameter. This function will be called when the process is done working (ie, onComplete): somefunction: function(callback){ var result = ""; myAjax = new Ajax.

What is returned by Ajax?

ajax() function returns the XMLHttpRequest object that it creates. Normally jQuery handles the creation of this object internally, but a custom function for manufacturing one can be specified using the xhr option.

What is the main role of JavaScript in an AJAX transaction?

Ajax interactions are initiated by JavaScript code. When the Ajax interaction is complete, JavaScript updates the HTML source of the page. The changes are made immediately without requiring a page refresh.


1 Answers

You should be able to do the following:

$.get($(this).attr("href"), $(this).serialize(), function(data){
   var script = $(data).text();
   eval(script);
});
like image 97
Jose Basilio Avatar answered Oct 22 '22 18:10

Jose Basilio