ajax教程栏目介绍实时刷新处理
推荐(免费):ajax教程(视频)
作为一个老前端,本案例是基于jquery来写的。
前端渲染页面拿数据,无非就是ajax、socket,其他的暂时没有用过,但项目还是使用ajax比较多。
下面来看一下一个简单基于ajax短轮询的请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function req() {
$.ajax({
type: 'get',
url: 'demo.php',
dataType: 'json',
success: function(res) {
console.log(res);
},
error: function() {
console.log('请求失败~');
}
});
}
req();
setInterval(req, 3000);
如果网速快而稳定的话,可以这样使用,但网速谁能确定呢,如果网速不稳定的话,请求一个接口需要5~10秒,这样就会造成ajax请求堆积,近而引发不可估量的问题,那么怎样去避免这个问题呢?
方式一:给请求赋上一个变量,然后每次轮询先abort掉上一个请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
var ajaxReq = null;
function req(isLoading) {
if(ajaxReq !== null) {
ajaxReq.abort();
ajaxReq = null;
}
ajaxReq = $.ajax({
type: 'get',
url: 'demo.php',
dataType: 'json',
beforeSend: function() {
if(isLoading) {
$('.zh-loading').show();
}
},
success: function(res) {
console.log(res);
},
complete: function() {
if(isLoading) {
$('.zh-loading').hide();
}
},
error: function() {
console.log('请求失败~');
}
});
}
req(true);
setInterval(function() {
req(false);
}, 3000);
猛一看,感觉还行,差不多就OK了,但作为前端的我们要不断的去寻找更合适的方式,所以有个下面这个。
方式二:每一次轮询都判断上一次请求是否完成,完成了才会执行下一次的请求(推荐)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var isLoaded = false;
function req(opts) {
$.ajax({
type: 'get',
url: 'demo.php',
dataType: 'json',
beforeSend: function() {
if(opts.init === 1) {
$('.zh-loading').show();
}
isLoaded = false;
},
success: function(res) {
console.log(res);
},
complete: function() {
if(opts.init === 1) {
$('.zh-loading').hide();
}
isLoaded = true;
},
error: function() {
console.log('请求失败~');
}
});
}
req({"init": 1});
setInterval(function() {
isLoaded && req({"init": 0});
}, 3000);
上面的 isLoaded && req({"init": 0}); 表示前面一个条件正确,则执行&&后面的方法
正常的写法是
1
if(isLoaded) req({"init": 0});
另外注意一点:isLoaded=true 要在complete里加,如果只在success里加的话, 请求失败了就不会轮询再请求了。complete不管success或error都会执行
代码就到这里了,thank you for attention~
相关免费学习推荐:javascript(视频)
快来看看 ajax实时刷新处理
最新推荐文章于 2022-08-07 15:39:41 发布