抱歉标题令人困惑。我无法用更好的方式来描述它。
这就是我想要找出的答案。这么说吧
function myClass()
{
$.ajax({
type:'get',
url:'some/path/',
success:function(response)
{
// call has been compeleted, set some flag here
}
});
return this;
}
var obj = new myClass();
jQuery('body').append('<div id="overlay"></div>'); // so now the user will know he has to wait for some operation to be completed...
// now determine on this line whether the Ajax call is still in progress
while(<ajax call still in progress>)
{
// i do not need to do anything here since the overlay is already there in place
}
// now this is where I want to remove the overlay
jQuery('#overlay').remove();
更新
基本上,我在进行 ajax 调用时显示加载覆盖层,一旦完成,我想删除该覆盖层。 我知道我可以在类本身内部编写代码,但我想要在类外部添加/删除覆盖层的控制权。
最佳答案
您应该使用此类请求的 promise 性质。所以保留一个引用内容
$.ajax
返回您创建的对象的属性。
然后,您可以对该属性使用 then
方法来了解所有操作何时完成。
以下代码调用测试服务器,在请求挂起时(1 秒)显示银色覆盖层:
function myClass(path) {
this.request = $.ajax({
// ^^^^^^^^^^^^
type: 'get',
url: path,
});
}
var obj = new myClass('https://httpstat.us/200?sleep=1000');
jQuery('body').append('<div id="overlay"></div>');
obj.request.then(function(response) {
console.log('done');
jQuery('#overlay').remove();
});
#overlay {
position: absolute;
width: 100%;
height: 100%;
background: silver;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
任何使此类代码同步的尝试都是不好的做法。您需要接受 Ajax 调用的异步特性,并使用回调系统,例如通过 Promise 提供的回调系统。
关于javascript - OOP 方法中是否可以知道 ajax 调用何时完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48300681/