Use the jquery global event ajaxstart to implement prompt effects for specific requests

Source: Internet
Author: User
Scenario

How can we achieve "ajaxstart" in a specific request?

First, the price for rewriting Ajax methods is too high, and jquery's own Ajax events can still be used.

Global events triggered by Ajax are transmitted to all DOM nodes like a standard event. Level: jquery events> Ajax events> Custom Ajax events.

Implementation
Wo = Window. wo | {}; wo. ajax = {spinner: $ ([]), init: function () {var $ spinner = This. spinner = $ ('# Ajax-loading'); var show = function (e) {If (E. namespace = 'wo') $ spinner. show () ;}; var hide = function (e) {$ spinner. hide () ;}; $ spinner. BIND ({'ajaxstart. wo': Show, 'ajaxstop. wo': Hide, 'ajaxerror. wo': Hide}); this. adapt (['getjson', 'get', 'post', 'ajax ']);} // initiate a request, _ prepare: function () {This. spinner. trigger ('ajaxstart. wo ');} // API batch change, adapt: function (FNS) {var self = This; $. each (FNS, function (I, FN) {WO [FN] = function () {self. _ prepare (); $ [FN]. apply (this, arguments );}});}};

There are two ways to determine whether the triggered event is a specific event:

  • The specified namespace.
  • When triggered, additional parameters are passed to the event handler.

Here, we use the namespace of the event to trigger the Source Judgment. The adapt method is equivalent to the application of the adapter and replaces another interface with a set of improved interfaces.

If you want to add the load method, it will be a little more troublesome, because it may be an Ajax method or an onload event of an element.

You need to add a proxy method and determine the type:

var _load = $.fn.load;$.fn.load = function() {$.type(arguments[0]) === 'string' && self._prepare();_load.apply(this,arguments);return this;};
Use

All method parameters are still consistent with the original one:

Wo.post(url, [data,] callback)

PS: there are better practices after jquery 1.5. For more information, see jquery Ajax routing and filter.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.