jQuery calls a common method summary for ajax requests

  • 2020-05-17 04:48:55
  • OfStack

This example summarizes common methods for jQuery to invoke ajax requests. Share with you for your reference. The details are as follows:

Example code 1


$.ajax('/ROUTE', {
 type: 'GET'
 data: {param1: 'Hello', param2: 'World'},
 dataType: 'json',
 contentType: 'application/json',
 timeout: 3000,
 success: function(response) {
  // console.log(response.something);
 },
 error: function(request, errorType, errorMessage) {
  // console.log("[" + errorType + "] " + errorMessage);
 },
 beforeSend: function() {
  // do something like .addClass('is-fetching')
 },
 complete: function() {
  // do something like removeClass('is-fetching')
 }
});

Example code 2


$.get('/ROUTE', function(response) {
 // success (response: HTML)
});
 
$.getJSON('/ROUTE', function(response) {
 // success (response: JSON)
});

Example code 3


$('form').on('submit', function(event) {
 event.preventDefault();
 var formData = $(this).serialize();
 $.ajax($(this).attr('action'), {
  type: $(this).attr('method'),
  data: formData,
  dataType: 'json',
  contentType: 'application/json',
  success: function(response) {},
  error: function(request, errorType, errorMessage) {},
  beforeSend: function() {},
  complete: function() {},
  timeout: 3000
 });
});

I hope this article has been helpful to your jQuery programming.


Related articles: