Application of ajaxPrefilter in jQuery


jQuery defines an ajax filter, ajaxPrefilter, through which ajax requests sent through the corresponding ajax function of jQuery can be filtered.

In the project, there is a need to specify the start time and end time to obtain the process line of some values changing with time in this time interval. We can define a general ajaxPrefilter to filter all ajax requests, and when the start time exceeds the end time, we will request the ajax to abort.

$.ajaxPrefilter(function (options, originalOptions, jqXHR) { //tm1 , tm2 Indicates the start time and end time
  var requestType, params, startTime, endTime;
  requestType = (originalOptions.type || "").toUpperCase(); //jsonp At the time of type For undefined
  if (requestType === "GET") {
    params = originalOptions.data ? $.param(originalOptions.data) : originalOptions.url;
  } else if (requestType === "POST") {
    params = $.param(originalOptions.data);
  }
  if (params) {
    startTime = params.match(/(^tm1|&tm1)=([^&#]*)/i) ? decodeURIComponent(params.match(/(^tm1|&tm1)=([^&#]*)/i)[2].replace(/\+/g, "%20")) : null;
    endTime = params.match(/(^tm2|&tm2)=([^&#]*)/i) ? decodeURIComponent(params.match(/(^tm2|&tm2)=([^&#]*)/i)[2].replace(/\+/g, "%20")) : null;
    if (startTime && endTime) {
      startTime = startTime.replace(/\-/g, "/");
      endTime = endTime.replace(/\-/g, "/");
      if (new Date(startTime).getTime() > new Date(endTime).getTime()) {
        jqXHR.abort();
        alert(" Start time cannot be greater than end time ");
      }
    }
  }
});