copenndthagen
copenndthagen

Reputation: 50732

Use of script returned from jQuery AJAX response

When we use script as the response for a jQuery/AJAX response, how does it help us ?

Can we directly execute a function of that response script once we make that AJAX request?

Any basic examples would be great.

Upvotes: 3

Views: 2290

Answers (3)

Mostafa Shahverdy
Mostafa Shahverdy

Reputation: 2725

You can use eval(scriptStrings); This is a basic function in javascript.

Also you can append those strings as an element to your current document to be evaluated, consider this code in mind:

function addJavascript(jsname,pos) {
  var th = document.getElementsByTagName(pos)[0];
  var s = document.createElement('script');
  s.setAttribute('type','text/javascript');
  s.setAttribute('src',jsname); 
  th.appendChild(s);
}

Upvotes: 3

user405398
user405398

Reputation:

jQuery getScript can be used to load any static script resource asynchronously. It executes the script as soon as it is downloaded. You can use the callback option to call any function from it.

But if your ajax response is a string. You have to use eval function. But before using it read some of these EVAL MDN, eval is evil.

Upvotes: 2

Raman
Raman

Reputation: 1376

Yes, we can use getScript method for fetching the script, it uses GET HTTP request to fetch and then execute the script. So you can directly execute the function of that response after the AJAX request. For more details and examples check jQuery documentation on this link http://api.jquery.com/jQuery.getScript/

Upvotes: 3

Related Questions