Difference between $ .ajax (), $ .get () and $ .load ()?

6

What is the difference between $.ajax() , $.get() and $.load() ?

What is the best to use and in what conditions?

    
asked by anonymous 24.09.2018 / 18:36

3 answers

7

$.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

    
24.09.2018 / 18:44
2

$.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 .

  • $.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);
    })
    
24.09.2018 / 20:08
1

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:

24.09.2018 / 20:14