将jQuery AJAX转换为回调

时间:2019-05-30 12:45:24

标签: javascript jquery ajax

在我的函数中,变量weekDaysDisabled在一个或多个AJAX调用增加变量之前显示。据我了解,我应该使用回调,但是我尝试了所有方法,但是无法转换函数。

你能帮我吗?非常感谢

还要记住,变量“ count”表示ajax函数为我提供了到对象位置1的数字的次数。

function nextWeek(flag) {
  var date = new Date($('#displayWeekDate').val());

  if (flag == 1) { // Next week
    $('#leftArrowAgenda').removeClass('passiveLeftArrowAgenda');
    $('#leftArrowAgenda').addClass('activeLeftArrowAgenda');
    date.setDate(date.getDate() + 7);
  } else {
    if (flag == -1) { // Previous week
      date.setDate(date.getDate() - 7);
    } else { // Current week
      date.setDate(date.getDate());
    }
  }
  if (flag == -1 && ('#leftArrowAgenda').hasClass('passiveLeftArrowAgenda')) {
    return;
  }

  dateString = date.toISOString().substring(0, 10);
  $('#displayWeekDate').val(dateString);

  var currentDate = new Date();
  currentDateString = currentDate.toISOString().substring(0, 10);
  if (flag == -1 && dateString == currentDateString) {
    $('#leftArrowAgenda').removeClass('activeLeftArrowAgenda');
    $('#leftArrowAgenda').addClass('passiveLeftArrowAgenda');
  }

  var dataSlot = 0;
  var flSlot = 0;
  var count = 0;
  var weekDaysDisabled = 0;
  var startOfWeek = moment(date).startOf('isoWeek');

  for (var i = 1; i < 6; i++) {
    flSlot = 0;

    if (i == 1) {
      dataSlot = startOfWeek;
    } else {
      dataSlot = startOfWeek.add(1, 'days');
    }

    if (some test) {
      flSlot = 1;
      weekDaysDisabled++;
    }

    if (flSlot == 0) {
      var dataAppuntamento = moment(dataSlot).format("YYYY-MM-DD");
      var idprof = $('#prof').val();
      $.ajax({
        url: 'php/slotAgenda.php',
        type: 'POST',
        data: {
          numSlot: i,
          dataAppuntamento: dataAppuntamento,
          idprof: idprof
        },
        dataType: 'html'
      }).done(function(data) {
        var obj = JSON.parse(data);
        if (isNaN(obj[1])) {
          count++;
          if (count == 1 && flag == 0) {
            some code
          }
        } else {
          weekDaysDisabled++;
        }
      }).fail(function() {
        alert('Si è verificato un errore, riprova...');
      });
    }
  }

  alert(weekDaysDisabled);
}

0 个答案:

没有答案