PHP+jQuery+Ajax+Mysql如何实现发表心情功能


实现发表心情功能通过php+jquery+ajax+mysql技术,大致流程我先给大家理下:主页index.html页面通过ajax获取心情图标及柱状图相关数据,当用户点击其中的一个心情图标时,向后台php发送请求,php对用户cookie验证(是否是首次提交),然后将数据库对应的心情字段内容加1,成功后返回前端页面,告诉首页index页面发表成功,并调整柱状图和统计数据。

请看效果图:

html:

先看HTML,我们在index.html中放置一个#msg,用来显示操作结果信息,#mood是操作主区域,其中ul通过javascript异步加载心情图标、说明、柱状图以及统计信息。

http://jquery.com/下载。
接着我们向mood.php发送Ajax请求,获取心情列表信息,并展示在index.html页面中。

$(function(){
 $.ajax({
 type: 'GET', //通过get方式发送请求
 url: 'mood.php', //目标地址
 cache: false, //不缓存数据,注意文明发表心情的数据是实时的,需将cache设置为false,默认是true
 data: 'id=1', //参数,对应文章或帖子的id,本例中固定为1,实际应用中是获取当前文章或帖子的id
 dataType: 'json', //数据类型为json
 error: function(){
 alert('出错了!');
 },
 success: function(json){ //请求成功后
 if(json){
 $.each(json,function(index,array){ //遍历json数据列
 var str = "<li><span>"+array['mood_val']+"</span><div class="pillar" 
style="height:"+array['height']+"px;"></div><div class="face" 
rel=""+array['mid']+""><img src="images/"+array['mood_pic']+"">
<br/>"+array['mood_name']+"</div></li>";
  $("#mood ul").append(str); //将数据加入到#mood ul列表中
  }); 
 }
 }
 });
 ...
});

这样,我们在访问index.html后,页面会载入心情列表,当然要想看到最终排列效果,还需要CSS,本文不讲解相关CSS,请下载源码或查看demo了解。
接下来,我们有个交互动作,当点击对应的心情图标时,图标被标识为已发表,柱状图高度发生变化,并且上面的数字会+1,表示发表成功,如果继续点击心情图标,会提示已经发表过不能重复提交。请看代码:

$(".face").live('click',function(){ //侦听点击事件
 var face = $(this);
 var mid = face.attr("rel"); //对应的心情id
 var value = face.parent().find("span").html();
 var val = parseInt(value)+1; //数字加1
 //提交post请求
 $.post("mood.php?action=send",{moodid:mid,id:1},function(data){
 if(data>0){
 face.prev().css("height",data+"px");
 face.parent().find("span").html(val);
 face.find("img").addClass("selected");
 $("#msg").show().html("操作成功").fadeOut(2000);
 }else{
 $("#msg").show().html(data).fadeOut(2000);
 }
 });
});

没看明白的童鞋可以下载源码仔细研究,点击文章开头的Download按钮即可下载,最后附上本例所需的mysql数据表结构,谢谢您的关注。

CREATE TABLE IF NOT EXISTS `mood` (
 `id` int(11) NOT NULL,
 `mood0` int(11) NOT NULL DEFAULT '0',
 `mood1` int(11) NOT NULL DEFAULT '0',
 `mood2` int(11) NOT NULL DEFAULT '0',
 `mood3` int(11) NOT NULL DEFAULT '0',
 `mood4` int(11) NOT NULL DEFAULT '0',
 `mood5` int(11) NOT NULL DEFAULT '0',
 `mood6` int(11) NOT NULL DEFAULT '0',
 `mood7` int(11) NOT NULL DEFAULT '0',
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `mood` (`id`, `mood0`, `mood1`, `mood2`, `mood3`, `mood4`, `mood5`, `mood6`, `mood7`)
VALUES(1, 8, 6, 20, 16, 6, 9, 15, 21);


« 
» 

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3