如何防止发送重复的ajax请求

时间:2017-06-27 01:23:12

标签: jquery ajax

如果第一次没有成功返回ajax请求,我想忽略第二个请求,直到第一个请求返回成功响应。

public static POST<T>(url: string, data): Promise<T> {
    var p = new Promise((resolve, reject) => {
        $.ajax({
            url: url,
            data: data,
            type: "POST",
            cache: false,
            success: function (response: HttpResponse) {
                   //success
            },
            error: function (response) {
                reject("error");
            }
        });
    });

    p.catch((err) => {
        //error
    });

    return p;
}

我已经解决了这个问题。代码如下:

var flag: { Url: string, Data: any }[];
flag = [];
public static POST<T>(url: string, data): Promise<T> {
  for (var i = 0; i < flag.length; i++) {
        if (flag[i].Url == url && CompareObjectEqual(flag[i].Data, data)) {
            return;
        }
    }
    var postInfo = {
        Url: url,
        Data: data
    };
    flag.push(postInfo);
  var p = new Promise((resolve, reject) => {
    $.ajax({
        url: url,
        data: data,
        type: "POST",
        cache: false,
        success: function (response: HttpResponse) {
               flag = [];
               //success
        },
        error: function (response) {
            reject("error");
        }
    });
  });

  p.catch((err) => {
    flag = [];
    //error
  });

  return p;
}

CompareObjectEqual的功能:

function CompareObjectEqual(a, b) {
  if (!(a instanceof Object && b instanceof Object)) {
    return a === b;
  }

  var aProps = Object.getOwnPropertyNames(a);
  var bProps = Object.getOwnPropertyNames(b);

  if (aProps.length != bProps.length) {
    return false;
  }

  for (var i = 0; i < aProps.length; i++) {
    var propName = aProps[i];
    if ((a[propName] instanceof Object) && (b[propName] instanceof Object)){
        CompareObjectEqual(a[propName], b[propName]);
    } else {
        if (a[propName] !== b[propName]) {
            return false;
        }
    }
  }

  return true;
}

1 个答案:

答案 0 :(得分:0)

我不确定你是如何调用promise的,但是你总是可以使用一个标志或变量来表示请求已被发送,然后在返回响应时切换该标志/变量。另外,我假设您正在使用Typescript,所以我使用该语法编写了我的响应。

postSubmitted = false;

public static POST<T>(url: string, data): Promise<T> {

    if (postSubmitted) { return };
    postSubmitted = true;

    var p = new Promise((resolve, reject) => {
        $.ajax({
            url: url,
            data: data,
            type: "POST",
            cache: false,
            success: function (response: HttpResponse) {
                postSubmitted = false;
                   //success
            },
            error: function (response) {
                postSubmitted = false;
                reject("error");
            }
        });
    });

    p.catch((err) => {
        //error
    });

    return p;
}