通过Ajax调用的轮询机制
Polling mechanism through an Ajax call
我需要添加轮询机制来通过我的网页调用web服务。为此,我尝试在javascript
页面中使用ajax
调用。我对ajax
和javascript
很陌生。我写了下面的代码。
<html>
<head>
<script language="JavaScript" type="text/javascript">
function pollServerForNewMail() {
setTimeout(function(){
$.ajax({ url: "server", success: function(data){
alert("TEST");
poll();
}, dataType: "json"});
}, 10000);
</script>
</head>
<body>
</body>
</html>
我需要的是每10秒启动一次警报测试。任何人都请帮我。
我将用我的两个jsp文件编辑这篇文章。
index.jsp文件
<html>
<table style="width:100%;text-align:center;'">
<tr>
<td style="text-align:center;width:100%">
<a href="polling.jsp?reset=true"><img src="images/import.png" /></a>
</td>
</tr>
</table>
</html>
polling.jsp文件
<html>
<head>
<script language="JavaScript" type="text/javascript">
function pollServerForNewMail() {
setTimeout(function(){
$.ajax({ url: "server", success: function(data){
alert("TEST");
poll();
}, dataType: "json"});
}, 10000);
}
pollServerForNewMail() ;
</script>
</head>
<body>
</body>
</html>
感谢
setTimeout
将只触发一次计时器。
使用setInterval
每X秒执行一次代码:
function pollServerForNewMail() {
setInterval(function(){
// Code in this function will run every 10 seconds
$.ajax({ url: "server", success: function(data){
alert("TEST");
poll();
}, dataType: "json"});
}, 10000);
}
我通过如下更改polling.jsp文件解决了问题。我将添加我的解决方案。
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
var set_delay = 5000,
callout = function () {
$.ajax({
/* blah */
})
.done(function (response) {
alert("TEST");
})
.always(function () {
setTimeout(callout, set_delay);
});
};
callout();
</script>
</head>
<body>
</body>
</html>
相关文章:
- 无法在通过jQuery的ajax加载的页面中执行javascript
- 如何通过ajax刷新JSF填充的javascript变量
- 如何在php文件中获取$.post-ajax传递的值
- Replacing $ .ajax?
- 在使用Polymer'加载所有json文件后执行方法;s的核心ajax
- Ajax发布表单序列化,发布引号'
- 通过Ajax将JavaScript函数传递给PHP文件
- ajax请求的顺序总是不同的
- 可以't使用Polymer's的核心ajax
- Ajax Live搜索发布到Laravel视图
- Ajax聊天消息重复而不仅仅是更新
- 从控制器返回后Ajax启动事件激发
- PHP AJAX图片上传示例不上传
- 从ajax请求中获取javascript对象
- 另一个ajax调用中的Jquery ajax调用在for循环中没有按预期工作
- 如何在Javascript中解析AJAX数组的特定部分
- 通过Ajax调用的轮询机制
- 现有的Web浏览器“chrond”(或等效)机制与JavaScript / AJax一起使用
- 如何用jQuery实现并发Ajax请求的发布和评论机制
- 应该从Rails服务器返回javascript (. JS .erb)还是在Ajax调用后更新页面时使用本机JS回调机制