将$ .ajax分配给变量并传递给$ .when

时间:2014-04-10 10:41:58

标签: jquery jquery-deferred

我正在努力实现的目标是对AJAX请求进行处理,并在完成这两项请求时使用响应更新DOM。代码如下:

  var prefix = container.data("lang");

  var typeList = $.ajax({
    url: "/" + prefix + "/camps/list/",
    data: {
      url: hashLink
    },
    type: "POST"
  });

  var typeData = $.ajax({
    url: "/" + prefix + "/camps/type",
    data: {
      url: hashLink
    },
    type: "POST",
    dataType: "JSON"
  });

  $.when(typeList, typeData).done(function(list, data) {
    console.log("we're done");
    //do something
  });

问题如下 - 我根本没有得到任何控制台日志。我做错了什么?

1 个答案:

答案 0 :(得分:0)

事实证明,使用fail方法进行错误检查是jQuery异步调用的一个非常好的主意。 所以,像我这样延迟工作:

$.when(typeList, typeData)
   .done(function(list, data) {
      console.log("we're done");
      //do something
   }).fail(function(list, data){
      console.log("Houston, we have a problem!");  
   });

给我省了很多麻烦,并为我提供了一些错误处理来启动。由于我们收到statusText作为回调函数的参数,因此很容易出错。