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?
The getScript() method is used to get and execute a JavaScript using an AJAX HTTP GET request.
getJSON() is equal to $. ajax() with dataType set to "json", which means that if something different than JSON is returned, you end up with a parse error. So you were mostly right about the two being pretty much the same :).
Pass the URL of JavaScript file in a <script> tag. Set the onload parameter, Trigger alert if script loaded. If not then check for loaded variable, if it is equal to false, then script not loaded.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With