准确的长轮询示例?
我创建了一个函数,应该进行长时间轮询并获取“推送”给我的实时数据。现在,我正在测试一个 json 对象,该对象的格式是我收到数据后的样子。到目前为止,它似乎工作正常。我只是想知道你对此有何看法?你会以某种方式重构它还是完全以另一种方式完成它?
var url = '../../path_to_script/respondents.json';
function fetchData() {
$.ajax({
url: url,
method: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
cache: false,
success: function (data) {
//parseData(data);
setTimeout(function () { fetchData() }, 5000);
console.log(data);
},
error: function (data) {
setTimeout(function () { fetchData() }, 5000)
}
});
}
问候
I've made an function that should do an long polling and fetch live data that is being "pushed" to me. Right now I'm testing against an json object that is formatted in the way that it will look once I receive the data. It seems as it is working accurate so far. I was merely wondering what you think about it? Would you refactor it somehow or do it entirely in another way?
var url = '../../path_to_script/respondents.json';
function fetchData() {
$.ajax({
url: url,
method: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
cache: false,
success: function (data) {
//parseData(data);
setTimeout(function () { fetchData() }, 5000);
console.log(data);
},
error: function (data) {
setTimeout(function () { fetchData() }, 5000)
}
});
}
Regards
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这就像预期的那样工作。由于您明智地选择在请求返回后触发
setTimeout
,因此不可能存在“重叠”请求。这是一件好事。无论如何,您可以使用 jQuery 的“新”延迟 ajax 对象,这可能更方便一些。
注意:
.always()
是全新的(jQuery 1.6)。编辑
示例:http://jsfiddle.net/rjgwW/6/
This works like expected. Since you've wisely choosen to fire a
setTimeout
once the request returned, there can't be "overlapping" requests. That is a good thing.Anyway, you could use jQuerys "new" deferred ajax objects which is probably a little bit more convinient.
Note:
.always()
is brandnew (jQuery 1.6).Edit
Example: http://jsfiddle.net/rjgwW/6/
我建议将事件更改为:
始终在成功和错误后调用完整事件。这样你就只会有一次 setTimeout 行,这样更好。
I suggest changing the events to:
The complete event is always called after success and error. This way you will only have the setTimeout line once, which is better.
我会做一些更改
method
更改为type
,method
不是$.ajax
的有效参数。这是一个错误contentType
,使用dataType: 'json'
足以让这些值。
希望这有帮助。干杯
I would do some changes
method
totype
,method
isn't a valid parameter for$.ajax
. This is an errorcontentType
, withdataType: 'json'
is enough to have those values.
Hope this helps. Cheers