3

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.

copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • 3
    Yes, look at the jQuery docs for Ajax. It has examples and it has a shortcut getScript. And why does it sound like we are answering homework questions for you? – epascarello Mar 19 '13 at 12:19
  • I'm wondering what you need it for. Perhaps you should transfer the function _name_ instead? – John Dvorak Mar 19 '13 at 12:22
  • Lots of questions remain, code would help clarify - do you actually add the script to the page? What does all this look like? – Mark Schultheiss Mar 19 '13 at 12:28

3 Answers3

3

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/

Raman
  • 1,336
  • 10
  • 13
3

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);
}
Mostafa Shahverdy
  • 2,687
  • 2
  • 30
  • 51
2

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.

Community
  • 1
  • 1