2014-05-06 39 views
1

这里是我的代码:数AJAX PHP的计数的按钮,点击计数器不显示

1/index.html的

<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> 

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文件中即HandleResponse函数应该让我向用户显示计数的数量。

我检查了txt文件,并跟踪了点击次数。但它从来没有在ResponseDiv中显示。我的意思是,应该显示点击次数时不会显示任何内容。 这里有什么问题?

+0

'if(xmlHttp.readyState == 4){HandleResponse(xmlHttp.responseText); } else {alert(xmlHttp.readyState); }做这个改变,这个警报是怎么说的? –

+1

你永远不会在脚本底部回显'$ clicks',只需添加'echo $ clicks;'。 – cmorrissey

+0

最好组织这样的问题: * 1 *:问题描述。 * 2 *:对代码示例的解释。 * 3 *:您的最后一段 – rpax

回答

0

我找到了解决方案。我只是补充道:{if(xmlHttp.readyState == 4){HandleResponse(xmlHttp.responseText); } else {HandleResponse(xmlHttp.responseText); }