我有以下代码:
index.html
function MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
else{HandleResponse(xmlHttp.responseText);}
}
xmlHttp.open("GET", "compteur.php", true);
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('text').innerHTML = response;
}
<span id="space" ><input onclick="MakeRequest();" type="button" value="PUSH" id="bouton"/></span>
<div id="text" >0</div>
count.php:
<?php
$fp = false;
// Open file for reading, then writing
while ( ($fp=fopen('nombre.txt','r+'))===false ) {
usleep(250000); // Delay 1/4 second
}
// Obtain lock
while ( !flock($fp, LOCK_EX) ) {
usleep(250000); // Delay 1/4 second
}
// Read Clicks
$clicks = trim(fread($fp,1024));
// Add click
$clicks++;
// Empty file
ftruncate($fp,0);
// Write clicks
fwrite($fp, $clicks);
// Release Lock
flock($fp, LOCK_UN);
// Release handle
fclose($fp);
echo $clicks;
?>
代码功能。每次按下按钮时,都会调用 MakeRequest 函数,并通过 count.php 函数增加 txt 文件中的计数。
我的问题是,当将计数写入txt文件时,每次计数之前也会写入NULL,并且当NULL太多时,计数会转到txt文件的第2行并返回到“1”。
我认为问题出在 xmlHttp.send(null); 我尝试了几种解决方案,包括 xmlHttp.send();但随后我的代码停止运行!!!
我的意思是,当单击按钮时,它不会在txt文件中写入“2”,然后再次单击按钮时写入“3”,而是写入“NULL 2”,然后写入“NULL NULL 3”。如何避免这种情况?
这一结果的一个很好的例子是:我的计数上升到 380,然后到 1,然后停止增加!
我如何确保我的计数不会在某个时刻突然重置为“1”?
最佳答案
现在我明白你想要的了,你的问题是由于 fopen 模式造成的。 http://www.php.net/manual/en/function.fopen.php
我认为这段代码应该可以工作。
<?php
$fp = false;
// Open file for reading, then writing
while ( ($fp=fopen('nombre.txt','r+'))===false ) {
usleep(250000); // Delay 1/4 second
}
// Obtain lock
while ( !flock($fp, LOCK_EX) ) {
usleep(250000); // Delay 1/4 second
}
// set pointer to begining of file
fseek($fp,0);
// Read Clicks
$clicks = trim(fread($fp,1024));
// Add click
$clicks++;
// Empty file
ftruncate($fp,0);
// set pointer to begining of file
fseek($fp,0);
// Write clicks
fwrite($fp, $clicks);
// Release Lock
flock($fp, LOCK_UN);
// Release handle
fclose($fp);
echo '|'.$clicks.'|';
?>
关于javascript - 由于 xmlhttp.send(NULL);,txt 中的计数被重置!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23593115/