我正在点击按钮上的点击次数。用php everythin工作。添加ajax后,单击按钮后我的页面崩溃了。我做错了什么?我插入了我的html,class和ajax代码。
<script type="text/javascript">
$(document).ready(function(){
$("#btn_like").click(function()
{
var counter;
counter+=1;
var counts={btn_like:like};
$.ajax({
type: "POST",
url: "ajax/count_likes.php",
data: counts
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
</script>
</head>
<body>
<form action="" method="post">
<div id="like">
<img id="aap" name="aap" src="images/aap.jpg" />
<input type="submit" name="btn_like" id="btn_like" value="I like"/>
<?php if (isset($likes)) {$numLikes=$likes->fetch_assoc();
echo "<span>"; echo $numLikes['likes_num']; echo "</span>"; }?>
</div>
</form>
这是班级
<?php
class User
{
private $m_sLike;
public function __set($p_sProperty, $p_vValue)
{
switch($p_sProperty)
{
case "Like";
$this->m_sLike = $p_vValue;
}
}
public function __get($p_sProperty)
{
$vResult = null;
switch($p_sProperty)
{
case "Like";
$vResult = $this->m_sLike;
break;
}
return $vResult;
}
public function getLikes()
{
include("Connection.php");
$sSql = "select * from tbllikes";
$result = $link->query($sSql);
return($result);
}
public function updateLikes()
{
include("Connection.php");
$sql = "UPDATE tbllikes SET likes_num=likes_num+1 WHERE likes_id=1";
$vResult = $link->query($sql);
}
}
?>
AJAX - 文件
<?php
include ('../classes/User.class.php');
if(isset($_POST['btn_like']))
{
$val=new User();
$val->Likes=$_POST['btn_like'];
$val->updateLikes();
//echo $val;
$likes=$val->getLikes();
}
header('Content-type: application/json');
echo json_encode($likes);
?>
答案 0 :(得分:3)
您没有阻止默认的提交按钮行为,因此它将执行正常的表单提交。
您可以使用preventDefault
来执行此操作
$("#btn_like").click(function(e)
{
e.preventDefault();
//Your rest of the code
});
http://api.jquery.com/event.preventDefault/
使用firebug并查看您是否遇到任何其他脚本错误。