文章主要介绍了php+mysql结合Ajax实现点赞功能,以一个完整实例形式详细分析了实现点赞功能中涉及的html页面、Ajax功能及php方法的使用技巧,非常具有实用价值,需要的朋友可以参考下。
要实现点赞功能,有多种实现方式,这里总结一下利用Ajax,php和mysql来实现点赞的数据的功能。具体步骤如下:
一、页面中的HTML代码部分:
?
1
2
3
4
5
6
7
8
9
10
11
<span>0</span>
<button onclick="goodplus(1);">good+1</button>
<span>0</span>
<button onclick="goodplus(2);">good+1</button>
<span>0</span>
<button onclick="goodplus(3);">good+1</button>
<span>0</span>
<button onclick="goodplus(4);">good+1</button>
二、写javascript
1、实现上面的button的.点击事件goodplus
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
var span = lementsByTagName('span');//获取存放点赞数的dom
var num; //点赞数
var flag = 0; //不同情况的标记
function goodplus(gindex){
flag = 1;
num = parseInt((gindex-1)rHTML);
if(checkcookie(gindex) == true){
num = num + 1;
senddata(gindex); //通过Ajax修改页面上的数据
}else{
alert("你已经点过赞咯!")
}
}
2、页面一打开时就应该更新点赞数据
?
1
2
3
for(var i = 1; i < th + 1; i++){
senddata(i);
}
3、通过Ajax获取数据senddata函数
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function senddata(aindex){
var xmlhttp;
var txt;
if(ttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("TTP");
}
adystatechange=function(){
if(yState == 4 && us == 200){
txt = onseText; //获取返回的数据
var cookieindex = aindex - 1;
lementsByTagName('span')(cookieindex)rHTML = txt; //赋值
}
}
("GET","路径/ + num + '&flag=' + flag + '&aindex=' + aindex,true);
();
}
4、通过设置cookie来判断是否已经点赞,如果有cookie则提示已经点赞,如果没有cookie则允许点赞,而且会设置cookie
?
1
2
3
4
5
6
7
8
9
10
11
12