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.

3
  • 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? Commented Mar 19, 2013 at 12:19
  • I'm wondering what you need it for. Perhaps you should transfer the function name instead? Commented Mar 19, 2013 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? Commented Mar 19, 2013 at 12:28

3 Answers 3

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/

Sign up to request clarification or add additional context in comments.

Comments

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);
}

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.