将javascript变量发布到PHP。

时间:2015-04-12 22:56:31

标签: javascript php html

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

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

这种实现对您来说是否正确,因为当我点击提交点击时,没有任何反应。我期待回复的点击次数。

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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>