减少 Ajax 请求

发布于 2025-01-06 11:40:22 字数 2853 浏览 5 评论 0原文

我正在使用 jQuery 和 JSON 制作聊天脚本,但我的托管由于“资源使用限制”而暂停了它。我想知道是否有可能(以及如何)减少这些请求。我读到一个问题,其中讲述了有关 Ajax 超时的信息,但我不太擅长 Ajax。代码是:

function getOnJSON() {
    var from;
    var to;
    var msg_id;
    var msg_txt;
    var new_chat_string;

    //Getting the data from the JSON file
    $.getJSON("/ajax/end.emu.php", function(data) {
        $.each(data.notif, function(i, data) {
            from = data.from;
            to = data.to;
            msg_id = data.id;
            msg_txt = data.text;
            if ($("#chat_" + from + "").length === 0) {
                $("#boxes").append('...some stuf...');
                $('#' + from + '_form').submit(function(){
                    contactForm = $(this);
                    valor = $(this + 'input:text').val();
                    destinatary = $(this + 'input[type=hidden]').val();
                    reponse_id = destinatary + "_input";
                    if (!$(this + 'input:text').val()) {
                        return false;
                    }
                    else {
                        $.ajax({
                            url: "/ajax/end.emu.php?ajax=true",
                            type: contactForm.attr('method'),
                            data: contactForm.serialize(),
                            success: function(data){
                                responsed = $.trim(data);
                                if (responsed != "success") {
                                    alert("An error occured while posting your message");
                                }
                                else {
                                    $('#' + reponse_id).val("");
                                }
                            }
                        });
                        return false;
                    }
                });

                $('#' + from + '_txt').jScrollPane({
                    stickToBottom: true,
                    maintainPosition: true

                });
                $('body').append('<embed src="http://cdn.live-pin.com/assets/pling.mp3" autostart="true" hidden="true" loop="false">');
            }
            else {
                var pane2api = $('#' + from + '_txt').data('jsp');
                var originalContent = pane2api.getContentPane().html();
                pane2api.getContentPane().append('<li id="' + msg_id + '_txt_msg" class="chat_txt_msg">' + msg_txt + '</li>');
                pane2api.reinitialise();
                pane2api.scrollToBottom();
                $('embed').remove();
                $('body').append('<embed src="http://cdn.live-pin.com/assets/pling.mp3" autostart="true" hidden="true" loop="false">');
            }
        });
    });
}

限制为 600 个请求/5 分钟,我几乎每秒都需要完成它。我已经支付了一年的费用,他们没有退款,而且我无法修改服务器,只能访问 cPanel

I'm making a chat script using jQuery and JSON, but my hosting suspends it due to 'resources usage limit'. I want to know if it is possible (and how) to reduce these requests. I read one question in which they tell something about an Ajax timeout, but I'm not very good at Ajax. The code is:

function getOnJSON() {
    var from;
    var to;
    var msg_id;
    var msg_txt;
    var new_chat_string;

    //Getting the data from the JSON file
    $.getJSON("/ajax/end.emu.php", function(data) {
        $.each(data.notif, function(i, data) {
            from = data.from;
            to = data.to;
            msg_id = data.id;
            msg_txt = data.text;
            if ($("#chat_" + from + "").length === 0) {
                $("#boxes").append('...some stuf...');
                $('#' + from + '_form').submit(function(){
                    contactForm = $(this);
                    valor = $(this + 'input:text').val();
                    destinatary = $(this + 'input[type=hidden]').val();
                    reponse_id = destinatary + "_input";
                    if (!$(this + 'input:text').val()) {
                        return false;
                    }
                    else {
                        $.ajax({
                            url: "/ajax/end.emu.php?ajax=true",
                            type: contactForm.attr('method'),
                            data: contactForm.serialize(),
                            success: function(data){
                                responsed = $.trim(data);
                                if (responsed != "success") {
                                    alert("An error occured while posting your message");
                                }
                                else {
                                    $('#' + reponse_id).val("");
                                }
                            }
                        });
                        return false;
                    }
                });

                $('#' + from + '_txt').jScrollPane({
                    stickToBottom: true,
                    maintainPosition: true

                });
                $('body').append('<embed src="http://cdn.live-pin.com/assets/pling.mp3" autostart="true" hidden="true" loop="false">');
            }
            else {
                var pane2api = $('#' + from + '_txt').data('jsp');
                var originalContent = pane2api.getContentPane().html();
                pane2api.getContentPane().append('<li id="' + msg_id + '_txt_msg" class="chat_txt_msg">' + msg_txt + '</li>');
                pane2api.reinitialise();
                pane2api.scrollToBottom();
                $('embed').remove();
                $('body').append('<embed src="http://cdn.live-pin.com/assets/pling.mp3" autostart="true" hidden="true" loop="false">');
            }
        });
    });
}

The limit is of 600 reqs/5 min, and I need to make it almost each second. I had a year already paid and they have no refund, also I can't modify the server, just have access to cPanel.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

吐个泡泡 2025-01-13 11:40:22

好吧,如果您想为每个用户每秒发出一个请求,那么 600 请求/5 分钟是相当严格的。本质上,这意味着每个用户每分钟将产生 60 个请求。或 300/5 分钟。换句话说,即使您优化脚本以将两个请求合并为一个,您的站点最多可以有两个用户;)我猜也不会太多...

您有两个选择:

  1. < p>坚持通过 Ajax 请求制作聊天系统并更改托管提供商。如果您不具备执行 2 的技能,这实际上可能会更便宜。

  2. 忘记发出 Ajax 请求进行轮询,并可能每秒发送另一个请求。围绕网络套接字、长轮询甚至 XMPP 实现一些东西。
    如果你走这条路,我会看看 socket.io 寻找一个使用 Web 套接字的透明库,并且支持它们其余的有长轮询和其他方法的后备方案。对于 XMPP 方式,有优秀的 Strope.js。请注意,这两个路由都比 Ajax 请求复杂得多,并且需要大量服务器逻辑更改。

Well, 600 req/5 min is pretty restrictive if you want to make a request/sec for each user. Essentially, that gives you that each user will make 60 req/min. Or 300/5 min. In other words, even if you optimize your script to combine the two requests to one, at maximum you can have two users at your site ;) Not much I guess...

You have two options:

  1. Stick with making a chat system through Ajax requests and change the hosting provider. This might be actually cheaper if you don't have the skills to do 2.

  2. Forget about making an Ajax request to poll and potentially another to push every second. Implement something around web sockets, long-polling or even XMPP.
    If you go that route, I would look at socket.io for a transparent library that uses web sockets where they are supported and has fallbacks to long polling and others for the rest. For the XMPP-way, there is the excellent Strophe.js. Note that both routes are much more complex than your Ajax requests and will require a lot of server logic changes.

夜司空 2025-01-13 11:40:22

我不认为每秒检查一次确实是一个好主意,在我看来,对于在线聊天 2/3 秒检查应该足够了。

为了减少请求,您还可以在客户端添加对用户活动的检查,如果窗口处于非活动状态,您可以延长检查时间,当用户恢复活动时回到 2/3 秒,这将允许您节省资源和请求/分钟

I don't think that checking each second is really a good idea, in my opinion for online chat 2/3 seconds check should be far enough.

To get less request, you can also add a check on the user activity in client side, if the windows is inactive you can lengthen the checking time, going back to 2/3 seconds when the user come back active, that will allow you to save resources and requests / minutes

忆伤 2025-01-13 11:40:22

我现在正在开发一个项目,需要使 UI 与服务器事件保持同步。我一直在使用长轮询,这确实减少了 ajax 调用的数量,但它给服务器带来了监听客户端感兴趣的事件的负担,这也不有趣。

我即将切换到 socket.io,我将其设置为单独的推送服务。

现有服务器 -->推送到 sockt.io 服务器 -->推送到订阅客户端

I'm working on a project right now that requires keeping the UI in sync with server events. I've been using long polling which does indeed reduce the number of ajax calls, but then it put's the burden on the server to listen for the event that the client is interested in, which isn't fun either.

I'm about to switch over to socket.io which I will set up as a separate push service.

existing server --> pushes to sockt.io server --> pushes to subscribing client

2025-01-13 11:40:22

ggozad 的反应很好,我也推荐网络套接字。它们仅适用于较新的浏览器模型,因此如果您想让它在所有浏览器上可用,您将需要一个小型 Flash 桥(Flash 可以非常轻松地与套接字通信,还可以调用 JavaScript 函数并从 JavaScript 调用)。另外,如果您有兴趣,Flash 还提供 P2P。 http://labs.adobe.com/technologies/cirrus/

另外,对于服务器端,您如果你是像我一样的 JavaScript 粉丝,可以查看 Node.js :)

来完成我的回复: 没有办法一个基于 Ajax 的聊天,您的请求限制为 600 个请求/5 分钟(2 个请求/秒),想要每秒发出一个请求,并且需要两个以上的用户。

解决办法:改用socket或者P2P。

ggozad's response is good, I also recommend web sockets. They work only with newer browser models, so if you want to make it available on all browsers you will need a small Flash bridge (Flash can communicate with sockets very easily and also it can call JavaScript functions and be called from JavaScript). Also, Flash offers P2P if you are interested. http://labs.adobe.com/technologies/cirrus/

Also, for server side you can look into Node.js if you are a JavaScript fan like me :)

To complete my response: there is no way to make an Ajax based chat in witch you are limited to 600 requests/5 min (2 requests/second), want to make a request/second and want more than two users.

Solution: switch to sockets or P2P.

瀞厅☆埖开 2025-01-13 11:40:22

我建议您使用单线程(作为 API 代理)从服务器端调用该付费服务。您仍然可以在此线程中以 600 个请求/5 分钟进行轮询。然后每个客户端都会无限制地向您的服务器 API 代理发送 Ajax 请求来轮询或长轮询。

I recommend you to call that paid service from the server side using a single thread (as an API proxy). You can still poll with 600 requests/5 min in this thread. Then every client do Ajax requests to poll or long-poll to your server API proxy without limitation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文