【问题标题】:How can I pass a callback function into an $.ajax.done callback?如何将回调函数传递给 $.ajax.done 回调?
【发布时间】:2013-06-06 03:18:45
【问题描述】:

我正在调用一个函数,它将ajax GET 发送到一个 url,如下所示:

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

mapUrl 将触发 Ajax 请求。在 Ajax donesuccess 处理程序中,我想触发我的回调函数,但这样做:

$.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
    }
  });

问题
所以我想知道如何将我的回调函数传递给ajaxdone-callback。知道怎么做吗?

谢谢!

编辑
这是完整的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;
};

【问题讨论】:

  • 能否分享方法声明`mapUrl
  • 一秒钟,即将到来
  • 你调用的方法?不确定是什么问题。显示您尝试过的内容。
  • callbackcallback是否有实际的传递方法?
  • 是的,我正在调用myplugin.mapUrl(window.location.href, function (d) {}, false); 我也得到了 OK 控制台,但我无法访问回调。

标签: javascript jquery ajax callback promise


【解决方案1】:

通常最好保留“promise”接口,而不是将回调传递到您的代码中。这将使您能够更好地捕获错误条件。

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

使用.then,您可以在将返回的数据传递给回调之前对其进行操作:

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

如果 AJAX 调用失败,此时您也可以链接其他 .fail 处理程序,这是您当前 API 不允许的。这种“关注点分离”可以让您放置更好的错误处理 UI,例如,不会将您的 AJAX 代码与 UI 相关的代码混淆。

【讨论】:

  • @frequent 很高兴能帮上忙! :)
猜你喜欢
  • 1970-01-01
  • 2013-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-02
  • 1970-01-01
相关资源
最近更新 更多