如何将此AJAX结构转换为使用.done而不是成功:

时间:2015-11-13 12:07:26

标签: jquery ajax twitter-bootstrap bootstrap-datetimepicker

我有一种情况,即传递给AJAX电话的日期等于“今天”#39;第一次请求页面时,并在用户使用日期选择器时进行更改。

我正在使用Jonathan Peterson的Bootstrap datetimepicker

https://github.com/Eonasdan/bootstrap-datetimepicker

在stackoverflow的一些帮助之后,它运行正常。

我根据这篇文章构建了我的代码:

http://jqfundamentals.com/chapter/ajax-deferreds

本文中的解决方案调用一个函数(下面的buildActivityCount)来处理成功的数据:

我的问题是:可以重写以下代码以使用.done而不是成功:?该代码目前工作正常。

$(document).ready(function () {

  var buildActivityCount = function (data) {
     // construct some html with the data and add to div
  }


   // This is the call when the datepicker is used

   $("#dpDashboard").on("dp.change", function (e) {

      fromDate = moment(e.date).format("DD-MM-YYYY");

      var ajaxOptions = {
             type: "POST",
             dataType: "json",
             url: "/Main/activityCount",
             data: { fromDate: fromDate },
             success: buildActivityCount
      }

      $.ajax(ajaxOptions);


  });

  // This is the call when the page first loads:

  var fd = new Date();
  var fromDate = moment(fd).format("DD-MM-YYYY");

  $.ajax({
    type: "POST",
    dataType: "json",
    url: "/Main/activityCount",
    data: { fromDate: fromDate },
    success: buildActivityCount
  });

  $.ajax(ajaxOptions);

}

谢谢!

1 个答案:

答案 0 :(得分:1)

非常容易。从您的选项中删除成功,并在ajax调用后添加.done()

  $(document).ready(function () {
      var buildActivityCount = function (data) {
      // construct some html with the data and add to div
      }
      // This is the call when the datepicker is used
      $("#dpDashboard").on("dp.change", function (e) {
          fromDate = moment(e.date).format("DD-MM-YYYY");
          var ajaxOptions = {
              type: "POST",
              dataType: "json",
              url: "/Main/activityCount",
              data: { fromDate: fromDate }
          }
      $.ajax(ajaxOptions).done(buildActivityCount);
      });
      // This is the call when the page first loads:
      var fd = new Date();
      var fromDate = moment(fd).format("DD-MM-YYYY");
      $.ajax({
          type: "POST",
          dataType: "json",
          url: "/Main/activityCount",
          data: { fromDate: fromDate }
      });
      $.ajax(ajaxOptions).done(buildActivityCount);
  }