Users frequently click send ajax request

If the user clicks frequently ajax request, there are two problems:

  1. If you clicked on five consecutive ajax requests, in fact, the first four are invalid, ending as early as possible to save resources.
  2. A more serious problem is: the last request sent, the response may not be the last one, is likely to cause confusion. Also you need to maintain a queue of requests and responses.

Direct termination ajax

终止ajax请求: 
var request = $.get("ajax.aspx",{id:1},function(data){ 
    //do something 
}); 

//终止请求动作. 
request.abort(); 

Preventing repeat request:

var request; 

if(request != null) 
    request.abort(); 

request = $.get("ajax.aspx",{id:1},function(){ 
    //do something 
}); 

If vue, or react, to be defined in the request for data or state inside.


setTimeout achieve ajax terminate secondTry after waiting one second of the firstTry:

var firstTry  = $.ajax( 
  //do something 
  ); 
var secondTry = setTimeout(function(){alert('ok');firstTry.abort()},1000);

for example:
Here Insert Picture Description

When users click on the thumbs up button frequently when:

        data: function () {
            return {
                status:0,
                xhrrequest: null
            };
        },
        methods: {
         setLike:function(){
		   this.doComment({
                    action: status
               },
               function (res) {
                   //回调函数数据处理
               }
           );
         },             
          doComment: function (opt, callback) {
                let _this = this;
                //let ajaxUrl = 'http://api.wmpvp.com';
                if (_this.xhrrequest != null)
                    _this.xhrrequest.abort();
                _this.xhrrequest = $.ajax({
                    type: "POST",
                    url: `${ajaxUrl}/XXXXXXX`,//接口地址
                    contentType: "application/json",
                    data: JSON.stringify({
                        accessToken: _this.isLogin(),
                        platform: "admin"
                    }),
                    dataType: "json",
                    success: function (res) {
                        callback && callback(res);
                    }
                });
            },
       }

Guess you like

Origin blog.csdn.net/qq_24147051/article/details/93161828