嗨,我遇到了一种情况,我必须以 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-loader 图像 asyn:false
最佳答案
不,这是不可能的。您无法从 async
调用返回 responseText
。因为 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
} );
还尝试寻找 promise 库:Q、Bluebird ...
解决问题的另一种方法是使用 Babel 的 async/await
。但是,据我所知,这种语法不是 es6 或 es7 的一部分。
关于javascript - 有没有办法使用 Jquery Ajax 获取具有 async true 的responseText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38201586/