Ajax轮询请求

时间:2023-03-09 18:01:05
Ajax轮询请求

Ajax轮询请求

什么是轮询?

  轮询(polling):客户端按规定时间定时向服务端发送ajax请求,服务器接到请求后马上返回响应信息并关闭连接。

  Ajax轮询需要服务器有很快的处理速度与快速响应。

Ajax轮询实现

Ajax轮询原理

客户端是按照规定时间(这个时间由你设定,此处默认为1秒)像服务端发送请求,前一次请求完成后,无论有无结果返回,一秒之后下一次请求又会发出。这就叫做Ajax轮询。

<script>
$(function(){
var code,status;
function getResult(){
var params = {
code: code,
operate: '什么操作TODO:',
};
$.ajax({
type: 'POST',
url: "请求地址TODO:",
data: params,
success: function(response) {
console.log('成功啦');
//对成功数据的操作TODO:
clearInterval(status);
},
dataType: 'json',
timeout: 30*1000,// 超时时间
// 超时意味着出错了
error: function (error) {
console.log('失败啦');
} });
} });
//获取code。如果code存在则调用轮询来获取数据
if(code){
status = setInterval(getResult, 1000);
} </script>

setInterval()用法:

 function direct() {
console.info( "time: ", ( new Date() ).getTime() );
}
function showlog() {
setInterval(direct(), 1000);
}
function showlog_2() {
setInterval( direct, 1000 );
}
function showlog_3() {
setInterval( function () {
direct();
}, 1000 );
}
function showlog_4() {
setInterval( "direct()", 1000 );
}
// showlog(); //=> 执行一次
// showlog_2(); //=> 每隔 1000毫秒 执行一次
// showlog_3(); //=> 每隔 1000毫秒 执行一次
// showlog_4(); //=> 每隔 1000毫秒 执行一次

长轮询

  ajax实现:在发送ajax后,服务器端会阻塞请求直到有数据传递或超时才返回。 客户端JavaScript响应处理函数会在处理完服务器返回的信息后,再次发出请求,客户端再次建立连接,周而复始

<script>
$(function() {
//定义code
var code;
//获取code TODO:
getStatusLong();
// 长轮询执行
function getStatusLong()
{
var data = {
operate: '操作TODO:',
code: code,
};
$.ajax({
type: 'post',
url: url,
data: data,
success: function(response) {
if (response.error == 0) {
//成功的操作
}
},
dataType: 'json',
timeout: 10*1000,// 超时时间
// 超时意味着出错了
error: function (error) {
console.log(error);// timeout
// 立即发出请求
getOrderStatusLong();
} }); }
});
</script>