我想在使用PHP和jquery的应用程序中实现反向Ajax。我已经在Google上搜索了一些内容,发现了XAJA,但似乎这是一个付费应用程序。是否有开源应用程序可用于相同的操作或者有人已经实现了此功能?任何指针或提示都将非常有帮助。谢谢!
我知道两种反向AJAX:
1- 轮询
2- 推送
我认为轮询比较容易实现,你只需要让你的javascript每隔一段时间向服务器发出一个常规请求,当服务器有数据时它会响应。这就像是一个ping,有些人称之为心跳,但这是解决这个问题的非常明显的解决方案。然而,它可能会过载服务器。
编辑 简单的轮询示例代码:
服务器端:
<?php
//pong.php php isn't my main thing but tried my best!
$obj = new WhatsNew();
$out = "";
if ($obj->getGotNew()){
$types = new array();
foreach ($obj->newStuff() as $type)
{
$new = array('type' => $type);
$types[] = $new;
}
$out = json_encode($types);
}
else{
$out = json_encode(array('nothingNew' => true));
}
客户端:
function ping(){
$.ajax(
{
url : "pong.php",
success : function (data){
data = JSON.parse(data),
if (data['nothingNew'])
return;
for(var i in data){
var type = data[i]['type'];
if (type && incomingDataHandlers[type]){
incomingDataHandlers[type]();
}
}
});
}
incomingDataHandlers = {
comments: function () {
$.ajax({
url: "getComments.php",
method: "GET",
data: getNewCommentRequsetData() // pass data to the server;
success : function (data){
//do something with your new comments
}
});
},
message: function (){
$.ajax({
url: "getMessages.php",
method: "GET",
data: getNewMessageRequestData() // pass data to the server;
success : function (data){
//do something with your new messages
}
});
}
}
$(docment).ready(function () {
setInterval(ping, 1000);
})
你可以结合使用“Flash” WebSockets 和WebSockets,因为几乎所有的浏览器都内置了Flash(平均约96%? => http://www.statowl.com/flash.php) => https://github.com/gimite/web-socket-js。你可以与http://code.google.com/p/phpwebsocket/一起使用。但我想知道性能是否会很好。如果可能的话,我会使用node.js来进行反向ajax。http://socket.io是一个非常酷的项目来实现这个!