Ajax长轮询问题

发布于 2024-11-29 14:39:48 字数 2049 浏览 1 评论 0原文

我查看了ajax长轮询的简要介绍这里并尝试模仿它在我自己的电脑上使用 wamp,但是我遇到了一些问题。

我一直收到有关 longpolling.php 文件中未定义索引的错误,第 29 行是

$num = $_GET['num'];
This was because there was one ajax get function that didn't have a num parameter resulting in $_GET not being set. I changed the code to

if(isset($_GET['num']))
    $num = $_GET['num'];
else
    $num = "";

效果很好。但是,一旦我重新加载页面,CD 计数就会减少一次,然后停止。

有谁知道发生这种情况的原因吗? php 文件(服务器)

<?php

$cd_stock = ("CdCount.txt");

function updateStock($num)
{
    global $cd_stock;
    $count = file($cd_stock);
    $count = (int)$count[0];
    $count = $count - $num;
    if ($count < 0) $count = 0;
    $fp = fopen($cd_stock , "w");
    fputs($fp , "$count");
    fclose($fp);

    echo $count;
}

function getCdCount()
{
    srand();
    $newOrder  = rand(1, 3);
    $sleeptime = rand(2, 10);
    sleep(2);

    updateStock($newOrder);
}
if(isset($_GET['num']))
    $num = $_GET['num'];
else
    $num = "";
if ( $num = "")
{
    getCdCount();
}
else
{
    updateStock((int)$num);
}
?>

javascript 文件(客户端)(使用原型框架)

Event.observe(window, 'load', function() {

    Event.observe( 'btnSubmit', 'click', purchaseCD);

    connectToServer();
});

function connectToServer()
{
    new Ajax.Updater(  
        { success: 'CD Count', failure: 'errors' },
        'LongPolling.php', 
        {
            method:     'get',
            onSuccess:  function(transport)
            {
                if (parseInt(transport.responseText)) connectToServer();
            }
    });
}

function purchaseCD()
{
    new Ajax.Updater(
        { success: 'CD Count', failure: 'errors' },
        'LongPolling.php', 
        {
            method:     'get',
            parameters: { num: $('txtQty').getValue() }
    });
} 

html 文件并不值得发布。它只包含ajax javascript文件和原型js文件以及相关的div等。

我已经绞尽脑汁试图解决这个问题,但我不知道出了什么问题,而且这并不令人鼓舞“教程”类型的文章。

I looked at a brief introduction to ajax long polling here and tried to mimic it on my own pc using wamp, however I have encountered a couple of problems.

I kept getting an error about undefined index in the longpolling.php file, line 29 which is

$num = $_GET['num'];

This was because there was one ajax get function that didn't have a num parameter resulting in $_GET not being set.
I changed the code to

if(isset($_GET['num']))
    $num = $_GET['num'];
else
    $num = "";

and that works fine. However, once i reload the page, the cd count decrements once and then stops.

Would anyone know the reason why this is happening?
php file (server)

<?php

$cd_stock = ("CdCount.txt");

function updateStock($num)
{
    global $cd_stock;
    $count = file($cd_stock);
    $count = (int)$count[0];
    $count = $count - $num;
    if ($count < 0) $count = 0;
    $fp = fopen($cd_stock , "w");
    fputs($fp , "$count");
    fclose($fp);

    echo $count;
}

function getCdCount()
{
    srand();
    $newOrder  = rand(1, 3);
    $sleeptime = rand(2, 10);
    sleep(2);

    updateStock($newOrder);
}
if(isset($_GET['num']))
    $num = $_GET['num'];
else
    $num = "";
if ( $num = "")
{
    getCdCount();
}
else
{
    updateStock((int)$num);
}
?>

javascript file (client) (uses prototype framework)

Event.observe(window, 'load', function() {

    Event.observe( 'btnSubmit', 'click', purchaseCD);

    connectToServer();
});

function connectToServer()
{
    new Ajax.Updater(  
        { success: 'CD Count', failure: 'errors' },
        'LongPolling.php', 
        {
            method:     'get',
            onSuccess:  function(transport)
            {
                if (parseInt(transport.responseText)) connectToServer();
            }
    });
}

function purchaseCD()
{
    new Ajax.Updater(
        { success: 'CD Count', failure: 'errors' },
        'LongPolling.php', 
        {
            method:     'get',
            parameters: { num: $('txtQty').getValue() }
    });
} 

The html file isn't really worth posting up. it just includes the ajax javascript file and the prototype js file and the relevant divs etc.

I've been racking my brain for hours trying to solve this but I have no idea what is wrong, and it is not encouraging that this is coming from a "tutorial" type article.

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

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

发布评论

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

评论(1

穿越时光隧道 2024-12-06 14:39:48

坦率地说,您的第一个问题可能存在于教程中,这一事实是不可原谅的。所有教程都应该假设您有最大的错误报告(如果所有教程都告诉您如何确保它发生,那就太好了)。这对你来说是个好消息吗? WAMP 默认情况下将错误报告设置得相当高,因此不用担心。

我还对他以这种方式使用 file (他应该使用 file_get_contents)这一事实表示怀疑,并且他告诉你要使用一个文件来开始 -它应该是$_SESSION,或者更好的是数据库连接。教程还应该通过一切必要的方式避免使用关键字 global (如果教程无法做到这一点,那么也许作者应该浏览教程而不是编写教程)。他还认为使用无效 CSS 的 ID 是个好主意(CSS 中的 ID 中不能有空格。这在 JS 中是可以接受的,但如果这会使 CSS 变得不可能,为什么要这样做呢)。最后,他讨论了 Ajax.Updater 的所有好处,但他决定使用奇怪的递归方案而不是 Ajax.PeriodicalUpdater这就是它的用途。

我的建议是放弃该教程并开发一个更好的教程。就我个人而言,我发现学习“旧方法”(无框架 AJAX)很有价值,我必须推荐 这个。如果你想使用框架,我个人认为你最好使用 jQuery 教程(例如 this一个),因为它更为常见。如果您真的喜欢 Prototype,还有其他更简单的示例 - 这个 似乎非常艰难。

如果您认为这是最重要的、真正的教程,那么您可以采取一些措施来帮助自己解决这个问题。您没有任何明显的编码错误,所以我最多可以给您建议:

  1. 确保 WAMP 仍在运行(我知道这是愚蠢的步骤,但有时我们中的很多人都会遇到这种情况)。
  2. 将 PHP 中的“sleep”替换为 if (parseInt(transport.responseText)) setTimeout(connectToServer, Math.rand() * 4000 + 1000); (将延迟放在客户端而不是服务器端)。 sleep 实际上应该只在极其罕见的情况下使用。
  3. transport.responseText 上调用 console.log(或者,如果您没有使用 Firebug 等 Web 开发工具(如果没有……为什么不呢?),则会发出警报)。如果服务器返回 0,则不会再次触发 connectToServer 方法。因此,了解该值可能会很有用。
  4. 跟踪 Ajax 请求。您可以使用 Firebug 免费执行此操作。
  5. 查看 CdCount.txt,看看它是否正在更新。

The very fact that your first problem could exist is a tutorial is, frankly, unforgivable. All tutorials should work with the assumption that you have maximum error reporting on (and it would be great if all of them told you how to ensure that it happened). The good news for you? WAMP sets error reporting pretty high by default, so there should be no worries there.

I also take issue with the fact that he is using file that way (he should be using file_get_contents) and that he is telling you to use a file to begin with -- it should be $_SESSION or, even better, a database connection. A tutorial should also avoid the use of the keyword global by all means necessary (and if a tutorial can't manage that, then maybe the author should be going through tutorials instead of writing them). He also thinks it a good idea for you to be using an ID which is invalid CSS (you can't have spaces in your ID's in CSS. It is acceptable in JS, but why would you do it if it makes CSS impossible). Finally, he talks about all of the benefit of Ajax.Updater, but he decides to use a bizarro recursion scheme instead of Ajax.PeriodicalUpdater. That's what it's there for.

My recommendation is to ditch that tutorial and work on a better one. Personally, I find value in learning "the old ways" (no-framework AJAX), I have to recommend this one. If you want to use a framework, personally I think you are better off with a jQuery tutorial (like this one) as it is far more common. If you really like Prototype, there are other, simpler examples -- this one seems very strait forward.

If you feel that this is the one, true tutorial, above all else, then there are some things you can do to help yourself sort this out. You don't have any glaring coding mistakes, so the most I can do is give you advise:

  1. Make sure WAMP is still running (stupid step, I know, but it happens to quite a few of us on occasion).
  2. Replace "sleep" in PHP with if (parseInt(transport.responseText)) setTimeout(connectToServer, Math.rand() * 4000 + 1000); (places the delay client-side instead of server-side). sleep should realistically only be used in extraordinarily rare circumstances.
  3. Call console.log (or alert if you're not using a web developer tool like Firebug (and if not... why not?)) on transport.responseText. If the server is returning 0, it won't fire the connectToServer method again. So knowing what that value is might be useful.
  4. Track the Ajax requests. You can do this with Firebug for free.
  5. Look at CdCount.txt, see if it is updating at all.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文