我不会用长轮询或任何东西使这变得过于复杂 - 为了让您开始,我假设您可以使用 setTimeout() 每 30 秒或其他时间检查新用户。坚持使用现有的 cats() 构造函数,您可以执行以下操作:
var cats = [];
function checkForNewCats() {
$.ajax({
url: "getcats.php",
data : { lastCat : (cats.length == 0 ? "" : cats[cats.length-1].name) }
})
.done(function(data) {
$.each(data, function(i, val) {
cats.push(new cat(val.name));
});
})
.fail(function() {
alert("Something went horribly wrong");
})
.always(function() {
setTimeout(checkForNewCats, 30000);
});
}
checkForNewCats();
这包括一个数组cats 来保存所有对象,然后是一个函数,它每分钟重复发出几次 ajax 请求以检查新猫并将它们添加到数组中。
这假设 PHP 返回的 JSON 是一个 cat 对象数组,类似于:
[
{ "name" : "fluffy" },
{ "name" : "sneezy" },
{ "name" : "ned" }
]
显然你可以为每只猫添加额外的属性。大概您的真实世界应用程序将具有某种用户 ID、名称和您提到的 GPS 位置。
我为 ajax 请求设置的data 属性:
data : { lastCat : (cats.length == 0 ? "" : cats[cats.length-1].name) }
基本上是通过最后一只猫的名字并将其留给 PHP,然后只返回自那只猫添加的猫的名字。显然,在现实世界的应用程序中,您会为此使用用户 ID 或记录时间戳。
编辑:jQuery Ajax 的旧语法 -
function checkForNewCats() {
$.ajax({
url: "getcats.php",
data : { lastCat : (cats.length == 0 ? "" : cats[cats.length-1].name) },
success : function(data) {
$.each(data, function(i, val) {
cats.push(new cat(val.name));
});
setTimeout(checkForNewCats, 30000);
}
});
}