【问题标题】:How can I convert this AJAX structure to use .done instead of success:如何将此 AJAX 结构转换为使用 .done 而不是成功:
【发布时间】:2015-11-13 12:07:25
【问题描述】:

我有一种情况,即传递给 AJAX 调用的日期在第一次请求页面时等于“今天”,并随着用户使用日期选择器而改变。

我正在使用 Jonathan Peterson 的 Bootstrap 日期时间选择器

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

它工作正常 - 在 stackoverflow 的帮助下。

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

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

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

我的问题是:下面的代码可以重写以使用 .done 而不是 success: 吗?该代码目前运行良好。

$(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);

}

谢谢!

【问题讨论】:

  • 当然。使用.done(...) 而不是传入success
  • $.ajax(ajaxOptions).done(buildActivityCount);$.ajax({ type: "POST", dataType: "json", url: "/Main/activityCount", data: { fromDate: fromDate } }).done(buildActivityCount);

标签: jquery ajax twitter-bootstrap bootstrap-datetimepicker


【解决方案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);
  }

【讨论】:

    猜你喜欢
    • 2021-06-10
    • 2011-04-23
    • 1970-01-01
    • 2022-01-01
    • 2016-11-12
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多