我有这个PHP脚本来计算按钮点击到txt文件
<?php
if (isset($_POST['clicks1'])) {
incrementClickCount1();
}
function getClickCount1() {
return (int) file_get_contents("count_files/clickcount1.txt");
}
function incrementClickCount1() {
$count = getClickCount1() + 1;
file_put_contents("count_files/clickcount1.txt", $count);
}
if (isset($_POST['clicks2'])) {
incrementClickCount2();
}
function getClickCount2() {
return (int) file_get_contents("count_files/clickcount2.txt");
}
function incrementClickCount2() {
$count2 = getClickCount2() + 1;
file_put_contents("count_files/clickcount2.txt", $count2);
}
?>
<?php
include ('counter.php');
?>
<div class="count_right"><?php echo getClickCount1(); ?></div>
<div class="count_left"><?php echo getClickCount2(); ?></div>
<form action="counter.php" method="post" >
<button type="submit" class="vote_right" name="clicks1" ></button>
<button type="submit" class="vote_left" name="clicks2"></button>
</form>
<小时/> 我正在尝试或想要做的是更新div上的计数但不刷新页面。
$('.vote_right, .vote_left').click(function(){
$.ajax({
url: 'counter.php',
type: 'post',
dataType:'html', //expect return data as html from server
data: $('.form1').serialize(),
});
});
我认为我有点乱,但这就是为什么我在这里:)
修改
谢谢你们,忘记提及..代码有效,但我的问题是:它
onSubmit="return false"
e.preventDefault();
答案 0 :(得分:0)
你应该使用ajax 的 HTML 强>
<?php
include ('counter.php');
?>
<div class="vote_right"><?php echo getClickCount1(); ?></div>
<div class="vote_left"><?php echo getClickCount2(); ?></div>
<form action="counter.php" method="post" >
<input type="button" class="vote_right" name="clicks1" >
<input type="button" class="vote_left" name="clicks2" >
</form>
<强> jquery的强>
$('.vote_right, .vote_left').click(function(){
class_count = $(this).attr("class");
count = $("."+class_count).text();
type = class_count == "vote_right" ? "right" : "left";
$.ajax({
url: 'counter.php',
type: 'post',
data: {"type": type,"count" : count},
success: function(data){
$("."+class_count).text(data);
}
});
});
在您的php中,您将获得$_REQUEST["type"]
(左侧或右侧)点击的按钮以及$_REQUEST["count"]
的此按钮的当前计数。在php文件的顶部添加这些行。
的 PHP 强>
if(isset($_REQUEST["type"]){
if($_REQUEST["type"] == "right" )
$_POST['clicks1'] = "1";
else
$_POST['clicks2'] = "1";
}
它应该完成你的工作;
答案 1 :(得分:0)
将e.preventDefault();
添加到您的点击处理程序:
$('.vote_right, .vote_left').click(function(e){
e.preventDefault();
$.ajax({
url: 'counter.php',
type: 'post',
dataType:'html', //expect return data as html from server
data: $('.form1').serialize(),
});
});