Javascript ajax php按钮单击计数器的计数不';不显示
这是我的密码: 1/index.htmlJavascript ajax php按钮单击计数器的计数不';不显示,javascript,php,ajax,Javascript,Php,Ajax,这是我的密码: 1/index.html <html> <head> <title>Example</title> </head> <body> <script type="text/javascript"> function getXMLHttp() { var xmlHttp try { xmlHttp = new XMLHttpRequest(); } catc
<html>
<head>
<title>Example</title>
</head>
<body>
<script type="text/javascript">
function getXMLHttp()
{
var xmlHttp
try
{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("AJAX not supported.")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "count.php", true);
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('ResponseDiv').innerHTML = response;
}
</script>
<input type='button' onclick='MakeRequest();' value='Button'/>
<br />
<br />
<div id='ResponseDiv'>
Count
</div>
</body>
例子
函数getXMLHttp()
{
var xmlHttp
尝试
{
xmlHttp=新的XMLHttpRequest();
}
捕获(e)
{
尝试
{
xmlHttp=新的ActiveXObject(“Msxml2.xmlHttp”);
}
捕获(e)
{
尝试
{
xmlHttp=新的ActiveXObject(“Microsoft.xmlHttp”);
}
捕获(e)
{
警报(“不支持AJAX”)
返回false;
}
}
}
返回xmlHttp;
}
函数MakeRequest()
{
var xmlHttp=getXMLHttp();
xmlHttp.onreadystatechange=函数()
{
if(xmlHttp.readyState==4)
{
HandleResponse(xmlHttp.responseText);
}
}
open(“GET”,“count.php”,true);
xmlHttp.send(空);
}
功能句柄响应(响应)
{
document.getElementById('ResponseDiv')。innerHTML=response;
}
计数
count.php:
<?php
$fp = false;
// Open file for reading, then writing
while ( ($fp=fopen('clicks.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);
?>
它是如何工作的:我点击按钮,AJAX函数调用php,增加点击次数,然后将其保存在txt文件中。HandlerResponse函数应该让我向用户显示计数的数量
我检查了txt文件,并跟踪了点击次数。但它从来没有显示在回应中。我的意思是,当点击次数应该显示时,什么也不显示。
这里有什么问题 我找到了解决办法。我刚刚添加了:{if(xmlHttp.readyState==4){HandleResponse(xmlHttp.responseText);}else{HandleResponse(xmlHttp.responseText);}
if(xmlHttp.readyState==4){HandleResponse(xmlHttp.responseText);}else{alert(xmlHttp.readyState);}
进行此更改,警报会说些什么?您永远不会回显$clicks
只需在脚本底部添加echo$clicks;
。最好这样组织问题:1:问题描述。2:解释,带有代码示例。3:您的最后一段警报说1,然后是2,然后是3,然后是n实际上正确地递增显示值。但是如何显示值而不显示警告1,2,3?我找到了解决方案。我只是添加了:{if(xmlHttp.readyState==4){HandleResponse(xmlHttp.responseText);}else{HandleResponse(xmlHttp.responseText);}