6

我希望在使用 PHP 和 jquery 的应用程序中实现反向 ajax。我用谷歌搜索了一下,发现了 XAJA,但这似乎是一个付费应用程序。是否有可用的开源应用程序或有人实现了它?

一些指针或提示会很有帮助。

提前致谢。

4

4 回答 4

1

我知道两种类型的反向 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);
})
于 2010-12-31T06:44:44.447 回答
1

您正在寻找他们所谓的“长轮询” - 我做了一个“长轮询 php”,我在堆栈溢出时得到了这个线程:

如何实现基本的“长轮询”?

于 2010-12-31T09:29:10.630 回答
0

您可以将 websockets 与“flash” 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是一个非常酷的项目!

于 2010-12-31T18:57:11.013 回答
0

你检查过APE吗?

它是一种基于推送的实时数据流技术,通过单个低容量 ajax 连接。这个概念很有用,你可以用你的服务器端实现来复制同样的东西

于 2012-03-13T07:22:03.390 回答