嗨,我有一种情况,我必须返回async true的responseText。
var initAjax = function (){
var customAjaxResponse = $.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function (xhr) {
$(".preloader div").removeClass('hide');
}
}).done(function (jsondata) {
$(".preloader div").addClass('hide');
try {
return jsondata;
} catch (e) {
generate("error", '<div class="activity-item"> \n\
<i class="fa fa-ban text-warning"></i> <div class="activity">Sorry! we are unable to find requested data, kindly try after some times.</div></div>');
}
}).error(function (jqXHR, exception) {
var error = "";
if (jqXHR.status === 0) {
error = "No internet Connection found.";
} else if (jqXHR.status == 404) {
error = "Page not found.";
} else if (jqXHR.status == 500) {
error = "Internal server error occurred.";
} else if (exception === 'parsererror') {
error = "JSON Parse error occurred.";
} else if (exception === 'timeout') {
error = "Your request has been timed out.";
} else if (exception === 'abort') {
error = "Ajax request has been aborted unexpectedly";
} else {
error = "Uncaught error occurred - " + jqXHR.responseText;
}
generate("error", '<div class="activity-item"> \n\
<i class="fa fa-ban text-warning"></i> <div class="activity">' + msg + '</div></div>');
});
return customAjaxResponse.responseText;
}
是否可以使用async:true返回数据,因为我无法显示任何ajax加载程序映像asyn:false
最佳答案
不,这不可能。您无法通过responseText
调用返回async
。因为initAjax
将结束执行,所以ajax
将从服务器获取内容之前。
解决此问题的常用方法是返回Promise
,然后等待其解析。
var initAjax = function (){
var customAjaxResponse = $.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function (xhr) {
$(".preloader div").removeClass('hide');
}
}).done(function (jsondata) {
//done
}).error(function (jqXHR, exception) {
//error
});
return customAjaxResponse.promise();
}
var promised_data = initAjax();
promised_data.then( function( response ){
//code to process response
} );
还尝试看一下承诺库的:Q,Bluebird ...
Library's Comparison
解决您的问题的另一种方法是使用Babel的
async/await
。但是,据我所知,此语法不是es6或es7的一部分。