JS代码:
- <script>
- function longPolling() {
- $.ajax({
- url: "testlp",data: { "time": 2,"timeout": 3 },//time:假设传输数据时间,timenout:最大延迟
- dataType:'JSON',success: function (data) {
- //输出data
- longPolling();
- }
- });
- }
- </script>
服务器代码:
- public string testlp(int time,int timeout)
- {
- // 死循环 查询有无数据变化
- while (true) {
- System.Threading.Thread.Sleep(1000);// 休眠1000毫秒
- int i = 1;
- if (i > timeout) { break; }//最大延迟
- else {
- i++;
- int compl = 1; //模拟数据库时间
- if (compl != time)//对比数据库中时间变化,此处一直进入if
- {
- string data= 数据库中数据
- // 返回数据信息,请求时间、返回数据时间、耗时
- //writer.print("result: " + i + ",response time: " + responseTime + ",request time: " + timed + ",use time: " + (responseTime - timed));
- return data;
- break; // 跳出循环,返回数据
- }
- }
- }
- return "false";//不会执行
- }