如何使用从异步函数接收的数据在Ajax调用中返回布尔值

时间:2018-01-15 03:45:13

标签: javascript jquery ajax

我试图在beforeSend进行数据验证。此数据验证应返回true或false。数据是从异步filereader.onloadend

接收的

如果为false,则该功能不应继续。但是使用下面的代码,它实际上会继续POST

var checkValidity = function(data, callback){
    const filereader = new FileReader()
    filereader.onloadend = function(e) {
        callback(e); // I want to do validation on data received here
    }
};

$('#imageField').on('change', function(e) {
    var formData = new FormData();

    $.ajax({
        data: formData,
        type: 'POST',
        beforeSend: function() {
            var data = formData.getAll('inputField');
            checkValidity(data, function(e){
                // if console.log(e) here, actually return expected value

                // I'm trying to return false/true here
                e ? return true : return false
            });
        }
    });
});

1 个答案:

答案 0 :(得分:3)

仅在成功验证后调用ajax

var checkValidity = function(data, callback) {
  const filereader = new FileReader()
  filereader.onloadend = function(e) {
    callback(e); // I want to do validation on data received here
  }
};

$('#imageField').on('change', function(e) {
  var formData = new FormData();

  var data = formData.getAll('inputField');
  checkValidity(data, function(e) {
    e ?
      return true: return false
  });


  If(conditionToCheckIfValid) {
    $.ajax({
      data: formData,
      type: 'POST',
      // rest of the code 
    });
  }
});