jQuery Ajax

 

We are here to talk about how the Ajax operation in jQuery is applied. If you are not too familiar with Ajax, you can first look at the instructions on Wikipedia .

jQuery jQuery.ajax()wraps (the lowest level) into the following common simple functions for Ajax Request; but if you have more complex requirements, you still need to use the ones mentioned later jQuery.ajax().

.load(url [, data] [, complete])

The load function is used to dynamically load an HTML file and insert it into the DOM. By default, this function sends the request by way of GET, but if the parameter data is set, it will be automatically converted to POST.

parameterTypeDescription
urlStringSpecify the address to call
dataMapKey/value pair to be passed to the server
completeFunctionThe callback to be called when the Ajax request is completed (does not need to be success)

For example, load the content of the ajax/test.html webpage into #result:

$('#result').load('ajax/test.html');

You can also have one more callback:

$('#result').load('ajax/test.html', function(responseText, textStatus, jqXHR) {
  // this - Point to #result DOM element
  // responseText - Requested file content
  // textStatus - Request status (success, error)
  // jqXHR - XMLHttpRequest Object
});

For the url parameter, we can also add a selector to filter the loaded HTML, that is, write the URL parameter type as follows url selector.

For example, load the content of the #container element in the ajax/test.html webpage into #result:

$('#result').load('ajax/test.html #container');

jQuery.get(url [, data] [, success] [, dataType])

$.get() A simple HTTP GET asynchronous request, if you want to execute some functions when an error occurs (error), then you have to use $.ajax().

parameterTypeDescription
urlStringSpecify the address to call
dataObjectKey/value pair to be passed to the server
successFunctionThe callback to be called when the Ajax request is completed (must be success)
dataTypeStringThe type of data returned-xml, html, script, json, jsonp, text. If you don't set it, jQuery will help you guess the format of the returned content.

For example, to get the content of ajax/test.html, if the returned content is JSON, jQuery will automatically parse it into a JavaScript object for you:

$.get('ajax/test.html', function(data) {
  $('.result').html(data.title);
});

You can also set the GET parameters of the url:

// Make an HTTP request test.php?name=John&time=2pm
$.get('test.php', {name: "John", time: "2pm"});

jQuery.post(url [, data] [, success] [, dataType])

$.post() is a simple HTTP POST asynchronous request function. If you want to execute some functions when an error occurs, you have to use $.ajax.

The usage of $.post() is the same as jQuery.get().

jQuery.getScript(url [, success])

Load JavaScript files through HTTP GET and execute the content automatically.

Usage example:

var url = 'https://code.jquery.com/color/jquery.color.js';
$.getScript( url, function() {
  // Do something after the script loads...
});

You can also use JSONP to make cross-domain requests. You need to add "url?callback=?" to the URL (you can also change the name instead of callback). When sending the request, the callback function The name "question mark?" will be automatically replaced by jQuery with a random function name (such as callback=jsonp1225116612487). On the server side, you can grab the value of the callback to send back the corresponding JSON to the browser for execution.

For example, grab data from the flickr API JSONP:

var flickerAPI = 'http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?';
$.getJSON(flickerAPI, {
  tags: 'mount rainier',
  tagmode: 'any',
  format: 'json'
}, function(data) {
  console.log(data);
})

jQuery Ajax events (Events)

You can set to trigger some different events customized by jQuery during the Ajax request process, which are divided into two categories-"global events" and "local events".

Local Events

Local events are events defined in the $.ajax() object (to be discussed later), such as:

$.ajax({
  beforeSend: function(){
    // The processing function when the beforeSend event occurs
  },
  complete: function(){
    // complete Handling function when the event occurs
  }
  // ...
});

Global Events

Global events is that you can bind Ajax Global Events to any element, and jQuery will trigger these events in a timely manner every time there is an Ajax request, such as:

$('#loading').bind('ajaxSend', function() {
  $(this).show();
}).bind('ajaxComplete', function() {
  $(this).hide();
});

List of all Global jQuery Ajax events

ajaxStart (Global Event) When
an Ajax request is generated and no other requests are running

beforeSend (Local Event)
before the Ajax request is sent

ajaxSend (Global Event)
Same as above

success (Local Event) When the
Ajax request is successful (without any error)

ajaxSuccess (Global Event)
Same as above

error (Local Event)
When an error occurs in the Ajax request (Ajax request is either a success or an error, there is no case)

ajaxError (Global Event)
Same as above

complete (Local Event)
Whether the Ajax request is success or error, the complete event will be triggered

ajaxComplete (Global Event)
Same as above

ajaxStop (Global Event) when
no Ajax request is running

The sequence of event triggering: ajaxStart »ajaxSend» ajaxSuccess or ajaxError »ajaxComplete» ajaxStop

jQuery.ajax(url [, settings])

This is the bottom Ajax object of jQuery, and the above mentioned are simple applications ($.get, $.post, etc.) wrapped by $.ajax(). $.ajax() has only one parameter, a key/value pairs object that contains initialization and processing Ajax request. The detailed parameter options settings are listed below:

parameter nameTypedefault valueDescription
asyncBooleantrueIs the same request
beforeSendFunction-Before sending the request, you can modify the XMLHttpRequest object here, such as adding a header, etc. You can cancel the Ajax request by returning flase in this function
cacheBooleantrue / false (if dataType is script or jsonp)Set to false to not capture old cached data from the browser
completeFunction-The function to execute when the request is completed (regardless of whether the result is success or error)
contentTypeStringapplication/x-www-form-urlencodedEncoding type for sending data to Server
dataObject, String, Array-The data sent to the server will be automatically converted to query string format, and if it is a GET request, it will be attached to the URL for you. The processData option can be used to disable this automatic conversion. The object type is Key/Value pairs
dataFilterFunction-Filter the data returned by the Server. The first parameter in the function is data, and the second is dataType.
function (data, type) {...}
dataTypeStringAutomatic judgment (xml or html)The type of data returned by the server is expected. If not specified, jQuery will automatically select responseXML or responseText to pass in your success callback according to the HTTP MIME Type. Optional data types are:
xml: return XML that can be processed by jQuery
html: return HTML, including script tags that jQuery will automatically process for you
script: return executable JavaScript. (Script will not be cached automatically unless cache is set to true
json: return JSON
jsonp: add callback=? parameter to the URL, and return this jsonp with the server side callback
text: return a plain text string
errorFunction-Execute function when request error occurs
globalBooleantrueSet whether to trigger global Ajax events
ifModifiedBooleanfalseJudged by the Last-Modified header, download only when the server updates the file
processDataBooleantrueSet whether to automatically convert data to query string
successFunction-Execute function when request is successful
urlStringCurrent URLSpecify the address to call
typeStringGETRequest method POST/GET

If the dataType option is specified, you have to make sure that the Server will return the correct MIME information (for example, the xml file is text/xml). The wrong MIME message will cause unexpected errors!

If you specify the dataType option as script, all cross-domain POST requests will be converted to GET, because jQuery uses script tags to download.

Usage For example, download and execute JavaScript files:

$.ajax({
  type: 'GET',
  url: 'test.js',
  dataType: 'script'
});

For example, to save data to the Server and notify the user that it has been saved:

$.ajax({
  type: 'POST',
  url: 'some.php',
  data: {name: 'John', location: 'Boston'},
  success: function(msg) {
    alert('Data Saved: ' + msg);
  }
});

Helper Functions

.serialize()

The content of the serialized form elements is a string in the format "name1=value1&name2=value3···".

$('form').on('submit', function(event) {
  event.preventDefault();
  console.log( $(this).serialize() );
});

.serializeArray()

The content of the serialized form element is an array in the format of [{name: name, value: value}].

$('form').on('submit', function(event) {
  event.preventDefault();
  console.log( $(this).serializeArray() );
});

The result of console.log will be an array with contents like:

[
  {
    name: "a",
    value: "1"
  },
  {
    name: "b",
    value: "2"
  },
  {
    name: "c",
    value: "3"
  },
  {
    name: "d",
    value: "4"
  },
  {
    name: "e",
    value: "5"
  }
]

jqXHR

After jQuery 1.5 version, all jQuery Ajax methods ($.get, $.post, $.ajax, ...) will return a jqXHR object, jqXHR is a superset of XMLHTTPRequest (superset), and at the same time implements the Promise The interface allows us to more easily manipulate asynchronous Ajax requests.

The jqXHR object has the following methods that can be used, and these methods themselves will return jqXHR so that you can facilitate chaining:

jqXHR.done(function(data, textStatus, jqXHR)

The Ajax call will be executed when it completes successfully.done() callback

jqXHR.fail(function(jqXHR, textStatus, errorThrown)

It will be executed when the Ajax call fails. fal() callback

jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown)

Ajax call will execute the .always() callback regardless of success or failure

jqXHR.then(function(data, textStatus, jqXHR) {}, function(jqXHR, textStatus, errorThrown)

When the Ajax call succeeds, the first parameter callback will be executed; when it fails, the second parameter callback will be executed.


Examples of usage:

// Ajax call can connect multiple processing functions in series
// and save the jqXHR returned by the function back to the jqxhr variable
var jqxhr = $.ajax('example.php')
  .done(function() {
    alert('success');
  })
  .fail(function() {
    alert('failure');
  })
  .always(function() {
    alert('End');
  });
 
// .....
 
// .done() .fail() .always() .then() can repeat call many times
// All callbacks will be executed sequentially
jqxhr.always(function() {
  alert('End part 2');
});

Post a Comment

0 Comments