我有1个POST ajax和1个GET ajax,我有这个:
$(document).ready(function () {
$(document).ajaxStart(function () {
$("#div28").show();
});
$(document).ajaxStop(function () {
$("#div28").hide();
});
});
这是为了显示LoadingGif,此时它显示了两个Ajax请求,所以如果只在POST类型ajax工作时才能显示LoadingGif?
修改 这是我的ajax功能:
$(document).ready(function () {
$.ajax({
contentType: "application/json; charset=utf-8",
type: 'GET',
url: 'api/Appointments/',
dataType: 'json',
success: function (result) {
if ((result.AppTime = "9:00") && (result.AppWithYritys = "Laakkonen")) {
document.getElementById("A9").style.background = "red";
}
else {
alert("error1");
}
},
error: function (error) {
alert("error");
},
});
});
和POST ajax:
var request = $.ajax({
type: "POST",
data: JSON.stringify(app),
url: "/api/Appointments",
contentType: "application/json",
dataType: "html"
});
request.done(function (data) {
if (data != -1) {
alert("You Have successfully made an appointment");
location.assign("http://tid.fi");
}
else {
alert("There has been an error!");
}
});
request.fail(function (gr) {
location.assign("http://google.com");
});
};
POST ajax是一个自定义函数,在按钮单击时触发。只是一个信息。
答案 0 :(得分:4)
使用ajaxSend
和ajaxComplete
,您可以看到"类型"请求是
但是,您也需要保留活跃请求的数量 - 可能不是您的简单页面所需要的 - 但这样做很好
$(document).ready(function () {
var started = 0;
$(document).ajaxSend(function (event, jqXHR, settings) {
if (settings.type == 'POST') {
if(!(started++)) { // only need to show on the first simultaneous POST
$("#div28").show();
}
}
});
$(document).ajaxComplete(function (event, jqXHR, settings) {
if (settings.type == 'POST') {
if(!(--started)) { // only hide once all simultaneous POST have completed
$("#div28").hide();
}
}
});
});
没有计数器的解决方案
$(document).ready(function () {
$(document).ajaxSend(function (event, jqXHR, settings) {
if (settings.type == 'POST') {
$("#div28").show();
}
});
$(document).ajaxStop(function () {
$("#div28").hide();
});
});
这将显示在POST上,并在所有ajax停止后隐藏 - 稍微不那么明显,但它可能只是一个有效的解决方案
答案 1 :(得分:1)
我认为最简单的选择是创建一个可以使用的小功能:
function showLoading(isLoading){
if(isLoading){
$("#div28").show();
}
else{
$("#div28").hide();
}
};
然后按照Ajax events
中的说明使用只需使用该功能,可以使用特定帖子的全局事件,也可以直接在beforeSend
和complete
事件挂钩上调用该函数。