我希望在我的应用程序中实现反向ajax,它使用PHP和jquery.我已经搜索了一下它并发现了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));
}
Run Code Online (Sandbox Code Playgroud)
客户端:
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);
})
Run Code Online (Sandbox Code Playgroud)