【发布时间】:2011-08-14 05:18:48
【问题描述】:
我查看了对 ajax 长轮询 here 的简要介绍,并尝试在我自己的电脑上使用 wamp 模拟它,但是我遇到了一些问题。
我一直在 longpolling.php 文件第 29 行收到关于未定义索引的错误
$num = $_GET['num'];这是因为有一个没有 num 参数的 ajax get 函数导致 $_GET 没有被设置。 我将代码更改为
if(isset($_GET['num']))
$num = $_GET['num'];
别的
$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 等。
我已经绞尽脑汁想解决这个问题好几个小时了,但我不知道出了什么问题,而且这来自“教程”类型的文章并不令人鼓舞。
【问题讨论】:
-
请在您的问题中添加代码/js/html 内联的相关部分。
-
好的,我已将它们内联,但是,我不知道问题所在,因此无法判断哪些部分相关或不相关。我希望我没有添加太多。
标签: php javascript ajax long-integer polling