What is the difference between $.ajax()
, $.get()
and $.load()
?
What is the best to use and in what conditions?
What is the difference between $.ajax()
, $.get()
and $.load()
?
What is the best to use and in what conditions?
$.ajax()
This is used to make asynchronous requests with any HTTP method, including GET
$.get()
It is the same as above but only for GET requests
The difference between the two above is that in the first you will have to pass an additional parameter
It's like$.load()
/ require
of PHP, it will simply add the result of the GET to the element, use it to split the application into components, and load it into < asynchronously
$.ajax
is the generic function to send an AJAX request, all other functions use it from behind two wads ( code );
The following functions were created to make programming easier, but they all call $.ajax
.
$.get(url [, data ] [, success ] [, dataType ])
(code ). Equivalent to:
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
$.post(url [, data ] [, success ] [, dataType ])
(code ). Equivalent to:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
$.getJSON(url [, data ] [, success ])
(code ). Equivalent to:
$.ajax({
url: url,
data: data,
success: success,
dataType: "json"
});
$.getScript(url [, success ])
(code ). Equivalent to:
$.ajax({
url: url,
success: success,
dataType: "script"
});
$.fn.load
this function differs from the previous ones because it is linked to some element and has a pre-defined callback . It calls the $.ajax
function, receives an HTML, and includes the HTML received in the element that this function was called ( code ). Example:
$('body').load('https://alguma.url.com/');
Has the same effect as:
$.get('https://alguma.url.com/', function(data) {
$('body').html(data);
})
The $.ajax
accepts, in addition to GET, POST and PUT requests, several other options that $.get
and $.load
do not have, because they are more simplified.
The $.ajax
and $.get
have the same function, that is, to make an HTTP request, but as said, the first can do GET, POST and PUT, while the second only GET. So if you need to do a POST or a PUT, for example, $.get
will no longer be useful.
$.load
loads the contents of a page into an element specified in the selector:
$("#resultado").load("pagina.php");
It will replace the HTML of the #resultado
(selector) element with the contents of pagina.php
.
But you can also use $.load
passing information via GET or POST:
Via GET (information passed directly in the URL):
$("#resultado").load("pagina.php?usuario=fulano");
Via POST (information passed via object {}
):
$("#resultado").load("pagina.php", {usuario: "fulano"});
Determining which method to use will depend heavily on the need for your application. You should also note the version of jQuery used because some options and callbacks have become obsolete and may vary from certain versions.
It's good to take a look at the documentation: