我试图在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
});
}
});
});
答案 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
});
}
});