如何将回调函数传递给$.ajax。做回调?

时间:2021-03-15 20:39:27

I'm calling a function, which makes an ajax GET to a url, like this:

我调用一个函数,它使一个ajax到达一个url,像这样:

// parameters = url, callback, boolean
that.mapUrl( window.location.search, function(spec) {
    console.log("initial mapping done");
    console.log(spec);
    // do stuff
  }, true);

mapUrl will trigger an Ajax request. Inside the Ajax done or success handler, I want to trigger my callback function, but doing it like this:

mapUrl将触发Ajax请求。在Ajax完成或成功处理程序中,我想触发回调函数,但是这样做:

$.ajax({
  method: 'GET',
  url: obj[1],
    context: $('body')
  }).fail(function (jqXHR, textStatus, errorThrown) {
    console.log("FAILED");
    configuration = {
      "errorThrown":errorThrown,
      "textStatus": textStatus,
      "jqXHR": jqXHR
    }    
  }).done(function(value, textStatus, jqXHR) {
    console.log("OK");
    console.log(callback) // undefined!
    configuration = {
      "value":value,
      "textStatus": textStatus,
      "jqXHR": jqXHR
    }
  });

Question:
So I'm wondering how to pass my callback function into the ajax done-callback. Any idea how to do this?

问题:所以我想知道如何将回调函数传递到ajax done-callback中。知道怎么做吗?

Thanks!

谢谢!

EDIT
Here is the full mapURL function

这里是完整的mapURL函数。

that.mapUrl = function (spec, callback, internal) {
  var key,
    obj,
    parsedJSON,
    configuration = {"root" : window.location.href};

  if (spec !== undefined && spec !== "") {
    obj = spec.slice(1).split("=");
    key = obj[0];
    console.log(key);
    switch (key) {
    case "file":
      $.ajax({
        method: 'GET',
        url: obj[1],
        context: $('body')
      }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log("FAILED");
        configuration = {
          "errorThrown":errorThrown,
          "textStatus": textStatus,
          "jqXHR": jqXHR
        }
      }).done(function(value, textStatus, jqXHR) {
        console.log("OK");
        configuration = {
          "value":value,
          "textStatus": textStatus,
          "jqXHR": jqXHR
        }
      });
      break;
    default:
      // type not allowed, ignore
      configuration.src = [];
      break;
    }
  }
  return configuration;
};

1 个解决方案

#1


3  

It would be generally better to preserve the "promise" interface rather than passing callbacks into your code. This will allow you to better trap error conditions.

最好是保存“承诺”接口,而不是将回调传递到代码中。这将允许您更好地捕获错误条件。

function mapUrl(url) {
    return $.ajax(...)
            .fail(...)
            .then(function(data) {
                // preprocess data and return it
            });
}

where using .then you can manipulate the returned data before it's passed to the callback:

使用后,您可以在返回的数据被传递给回调之前操作返回的数据:

mapUrl(...).done(function(data) {
    // data has been preprocessed
    ...
});

If the AJAX call fails, you can chain additional .fail handlers at this point too, which your current API would not permit. This "separation of concerns" would let you put nicer error handling UI in place, for example, without cluttering your AJAX code with UI-related code.

如果AJAX调用失败,您还可以在这一点上添加额外的.fail处理程序,您当前的API不允许这样做。这种“关注点分离”会让你在处理UI的时候放置更好的错误,例如,无需使用与UI相关的代码来处理AJAX代码。

#1


3  

It would be generally better to preserve the "promise" interface rather than passing callbacks into your code. This will allow you to better trap error conditions.

最好是保存“承诺”接口,而不是将回调传递到代码中。这将允许您更好地捕获错误条件。

function mapUrl(url) {
    return $.ajax(...)
            .fail(...)
            .then(function(data) {
                // preprocess data and return it
            });
}

where using .then you can manipulate the returned data before it's passed to the callback:

使用后,您可以在返回的数据被传递给回调之前操作返回的数据:

mapUrl(...).done(function(data) {
    // data has been preprocessed
    ...
});

If the AJAX call fails, you can chain additional .fail handlers at this point too, which your current API would not permit. This "separation of concerns" would let you put nicer error handling UI in place, for example, without cluttering your AJAX code with UI-related code.

如果AJAX调用失败,您还可以在这一点上添加额外的.fail处理程序,您当前的API不允许这样做。这种“关注点分离”会让你在处理UI的时候放置更好的错误,例如,无需使用与UI相关的代码来处理AJAX代码。