The difference between $ .getScript () and $ .get ()

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

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

It seemed to me that with $.getScript you can send data to the server (as with the $.get function), but you cannot receive data from the server (which you can with the $.get function). But this shows in the $.getScript documentation a few lines below in the first example that you can also get data with the console.log(data); //data returned console.log(data); //data returned .

So what is the difference? Is it $.getScript that with $.getScript you can only call js scripts and $.get you can call any file? What are the limitations / benefits of using one function instead of another?

+7
source share
2 answers

Both of these are shortcuts to calling the ajax function. jQuery.get equivalent to:

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

So far, jQuery.getScript equivalent:

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

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

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

+18
source

getScript designed to load a script. When you add the script from the script, it will load the asynchronous script. If you use getScript , you can set a callback function to terminate another script.

$.get is a basic ajax request, you can do what you want with it. This is completely for you.

+1
source

All Articles