2015-04-12 84 views
1

我有一个javascript函数来计算点击次数。我希望将存储计数的变量发布到PHP。我不确定为什么当我提交表格时,计数没有被回应。以下是HTML文件。将一个javascript变量发布到PHP。

<html> 
<head> 
<title> js php </title> 
<script> 
    var cnt=0; 
    function CountFun(){ 
    cnt=parseInt(cnt)+parseInt(1); 
    var divData=document.getElementById("showCount"); 
    divData.innerHTML="Number of Downloads: ("+cnt +")";//this part has been edited 

    } 
</script> 
</head> 
<body> 

<div id="showCount"></div> 
<form action "submitClicks.php"id="form"> 
    <input type="hidden" name="numberOfClicks" /> 
    <input type="button" id="btnClick" value="Click me" onclick="CountFun()"/> 
    <input type="submit" value="Submit Clicks" /> 
</form> 

</body> 
</html> 

然后,这是我的提交页面点击:

<?php 
    $number_of_clicks = $_POST["cnt"]; 
    echo $number_of_clicks; 
?> 

这是否实施看起来是正确的给你,当我点击提交点击,什么都不会发生。我期待点击次数得到回应。

+0

什么是 “没有任何反应” 是什么意思?你看到什么了吗?它每次都是零或什么? –

+0

@ t_01当我点击“点击我”时,数字被计数并显示出来。当我提交点击时,网址从http://localhost/clicks/count.html更改为http://localhost/clicks/count.html?numberOfClicks =,但不显示带有点击次数的回显。 –

回答

1
<form action "submitClicks.php"id="form"> 

应该是:

<form action="submitClicks.php" id="form" method="post"> 

而且你不应该有这样的事情:

在HTML:

<input id="count" type="hidden" name="cnt" value=""> 

在JavaScript CountFun功能:

document.getElementById('count').value = cnt; 
+0

这只是从URL中删除数据,这不是一个真正的问题。我试图让cnt javascript变量在PHP文件中回显。 –

+0

我编辑了我的帖子。在你的代码中,你实际上并没有添加要由表单提交的计数值。 –

+0

@joemartin如果你没有指定你想要使用post,你不能在你的php中使用_POST。 –

0

试试这个代码:

<html> 
<head> 
<title> js php </title> 
    <script> 
     var cnt=0; 
     function CountFun(){ 
     cnt=parseInt(cnt)+parseInt(1); 
     var divData=document.getElementById("showCount"); 
     divData.value=cnt;//this part has been edited 
     document.getElementById("JustShow").innerHTML= cnt; 
     } 
    </script> 
</head> 
<body> 


<div id="JustShow"></div> 
<form action="submitClicks.php" id="form" method="post"> 
    <input type="hidden" id="showCount" name="cnt" value="0" /> 
    <input type="button" id="btnClick" value="Click me" onclick="CountFun()"/> 
    <input type="submit" value="Submit Clicks" /> 
</form> 

</body> 
</html> 
+0

当我提交点击但是PHP给出这个错误时,这会把cnt放到URL栏中:$ number_of_clicks = $ _POST [“cnt”];而不是回声。 –

+0

只需将表单标签更改为:

Basem