How JS Ajax requests prevent duplicate submissions

  • 2021-06-28 10:32:32
  • OfStack

I haven't written js code for a long time and I happen to encounter this problem.Most forms in our system are not designed to prevent duplicate submissions.

Since you don't want to work on this side of the back end, if handled by the back end, you need to give a one-time token value when the page loads, which increases the workload of development and makes it easy to forget to do this. ajax is also not handled and returns a new token value if the submission fails.

So I want to do it on js's side.In fact, it was mentioned before and at the front end that after a long period of inactivity, we had to throw out a brick.The idea is to override $.ajax, which addresses issues that prevent duplicate submissions, while business development on the front end is unaffected, code-free, and insensitive.

I think the first purpose of the architecture is to simplify business development, shield business-independent details, and let the first line of development write business.

The code is as follows:


/**
* Created by xiayongsheng on 2016/6/12.
*/
;(function($){
var ajax = $.ajax;
//  For storage ajax Request for 
var ajaxState = {};
var kinhomAjax = function () {
var args = Array.prototype.slice.call(arguments, 0);
// url data 1 To, 
//  You should add  url Take it out, data Sort key values, then stitch values together 1 Start, proceed sha1 The resulting value as a fingerprint 
//  Pre-use  url As fingerprints 
var hash = typeof args[0] === 'string'?args[0]:args[0].url;
if (typeof ajaxState[hash] !== 'undefined') {
if (ajaxState[hash] > 3) {
alert(' Please do not submit again, request is in progress ');
}
++ajaxState[hash];
return $.Deferred();
}
ajaxState[hash] = 1;
var def = ajax.apply($,args);
def.done(function () {
delete ajaxState[hash];
});
return def;
};
$.ajax = kinhomAjax;
})(jQuery);

Related articles: