最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use of script returned from jQuery AJAX response - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question asked Mar 19, 2013 at 12:17 copenndthagencopenndthagen 50.9k105 gold badges313 silver badges492 bronze badges 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? – epascarello Commented Mar 19, 2013 at 12:19
  • I'm wondering what you need it for. Perhaps you should transfer the function name instead? – John Dvorak 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? – Mark Schultheiss Commented Mar 19, 2013 at 12:28
Add a ment  | 

3 Answers 3

Reset to default 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./jQuery.getScript/

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

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.

发布评论

评论列表(0)

  1. 暂无评论