Difference between $.getScript() and $.get()

我只是一个虾纸丫 提交于 2021-02-08 13:27:22

问题


I am trying to understand what are the differences between $.getScript function in jQuery and the $.get.

According to the documentation: http://api.jquery.com/jQuery.get/ and http://api.jquery.com/jQuery.getScript/

It gave me the feeling that with the $.getScript you can send data to the server (as with the $.get function) but you can't get data from the server (which you can with the $.get function). But it shows in the documentation of $.getScript, some lines below in the first example, that you can get also data with the line console.log(data); //data returned.

So what is the differences? Is it that with $.getScript you can call only js scripts and with $.get you can call whatever file? What are the restrictions / benefits of using one function instead of the other?


回答1:


Both of these are shortcuts to ajax function call. jQuery.get is equivalent to:

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

While jQuery.getScript is equivalent to:

$.ajax({
  url: url,
  dataType: "script",
  success: success
});

It is easy to see that jQuery.get can obtain any response type (script, xml, json, script, or html - by default html), and getScript is limited to "script".

In short, getScript is used to dynamically execute external JavaScript, and get is general purpose function usually used to receive data according to params passed. However, it is also possible to pass params in getScript (in URL) but that will be not common, because most scripts are static. Finally callback in getScript can be used to execute final statements after our script was executed (for example, use some library function after loading it).




回答2:


getScript is designed to allow you to load a script. When you append a script from within a script, it will load the script asynchronous. If you use getScript, you can set a callback function for when the other script has completed running.

$.get is a basic ajax request, you can do what you want with it. It's completely up you.



来源:https://stackoverflow.com/questions/8110898/difference-between-getscript-and-get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!