Home > Web Front-end > JS Tutorial > How does PHP jQuery Ajax Mysql implement the mood expression function_javascript skills

How does PHP jQuery Ajax Mysql implement the mood expression function_javascript skills

WBOY
Release: 2016-05-16 15:46:36
Original
1611 people have browsed it

The function of posting mood is implemented through php jquery ajax mysql technology. Let me explain the general process first: the homepage index.html page obtains mood icons and histogram related data through ajax. When the user clicks on one of the mood icons, the The background PHP sends a request, PHP verifies the user cookie (whether it is submitted for the first time), and then adds 1 to the corresponding mood field content in the database. After success, it returns to the front-end page, tells the homepage that the index page has been published successfully, and adjusts the histogram and statistical data.

Please see the rendering:

html:

Looking at the HTML first, we place a #msg in index.html to display the operation result information. #mood is the main operation area, where ul loads mood icons, descriptions, histograms and statistical information asynchronously through javascript.

Copy code The code is as follows:






    PHP
    First, we configure the database connection information and example-related parameters in the config.php configuration file.
    $

    host="localhost";
    $db_user="root";
    $db_pass="";
    $db_name="demo";
    $link=mysql_connect($host,$db_user,$db_pass);
    mysql_select_db($db_name,$link);
    mysql_query("SET names UTF8");
    //心情说明,用半角逗号隔开
    $moodname='震惊,不解,愤怒,杯具,无聊,高兴,支持,超赞';
    //心情图标文件,用半角逗号隔开(template/images/目录)
    $moodpic='a1.gif,a2.gif,a3.gif,a4.gif,a5.gif,a6.gif,a7.gif,a8.gif';
    //统计心情柱图标最大高度
    $moodpicheight=80;
    
    Copy after login

    Next, we are going to divide mood.php into two parts. By receiving the action parameters, we can divide it into the first part: expressing the mood, and the second part: obtaining mood-related information.

    Copy code The code is as follows:

    include_once("config.php");
    $action = $_GET['action'];
    if($action=='send'){ //Express your mood
    ...
    }else{ //Get mood
    ...
    }

    Part1: Express your mood.
    Users submit mood parameters via post from the front end, including article id and mood id. First verify whether the article exists, then verify whether the user has posted a mood about this article, then operate the database, set the corresponding mood field value to 1, and calculate the height of the histogram corresponding to the current mood, and return it to the front-end js for reception .

    $id = (int)$_POST['id']; //文章或帖子id
    $mid = (int)$_POST['moodid']; //心情id(配置文件中提供8种心情)
    if(!$mid || !$id){
     echo "此链接不存在";exit;
    }
    $havemood = chk_mood($id); //验证cookie
    if($havemood==1){
     echo "您已经表达过心情了,保持平常心有益身心健康!";exit;
    }
    $field = 'mood'.$mid; //数据表中的心情字段,分别用mood0,mood1,mood2...表示不同的心情字段
    $query = mysql_query("update mood set ".$field."=".$field."+1 where id=".$id); //对应的心情字段值+1
    if($query){
     setcookie("mood".$id, $mid.$id, time()+300); //设置cookie,为了测试我们设置cookie过期时间为300s
     $query2 = mysql_query("select * from mood where id=$id");
     $rs = mysql_fetch_array($query2);//获取该文章的心情数据
     $total = $rs['mood0']+$rs['mood1']+$rs['mood2']+$rs['mood3']+$rs['mood4']+$rs['mood5']+
    $rs['mood6']+$rs['mood7'];
     $height = round(($rs[$field]/$total)*$moodpicheight); //得到总量,并计算当前对应心情的柱状图的高度
     echo $height; //返回当前心情柱状的高度
    }else{
     echo -1; //数据出错
    }
    
    Copy after login

    To verify whether the user has posted a mood, we use the function chk_mood() to determine whether the user's corresponding cookie exists.

    //验证是否提交过
    function chk_mood($id){
     $cookie = $_COOKIE['mood'.$id];
     if($cookie){
     $doit = 1;
     }else{
     $doit = 0;
     }
     return $doit;
    }
    
    Copy after login

    Part2: Get mood
    By obtaining the mood data corresponding to the article or post ID in the data table, the value corresponding to each mood is obtained (which can be understood as the number of times the mood is posted), and the height of the histogram is calculated, and the value, name, icon, and The height information is constructed into an array, and finally returned to the front end as JSON format data.

    $mname = explode(',',$moodname);//心情说明
    $num = count($mname);
    $mpic = explode(',',$moodpic);//心情图标
    $id = (int)$_GET['id']; //文章或帖子id
    $query = mysql_query("select * from mood where id=$id"); //查询对应的心情数据
    $rs = mysql_fetch_array($query);
    if($rs){
     //得到发表心情的总量
     $total = $rs['mood0']+$rs['mood1']+$rs['mood2']+$rs['mood3']+$rs['mood4']+
    $rs['mood5']+$rs['mood6']+$rs['mood7'];
     for($i=0;$i<$num;$i++){
     $field = 'mood'.$i; //字段名
     $m_val = intval($rs[$field]); //心情对应的值(次数)
     $height = 0; //柱图高度
     if($total && $m_val){
     $height=round(($m_val/$total)*$moodpicheight); //计算高度
     }
     
     $arr[] = array(
     'mid' => $i, //对应心情id
     'mood_name' => $mname[$i], //心情名称
     'mood_pic' => $mpic[$i], //图标
     'mood_val' => $m_val, //次数
     'height' => $height //柱状图高度
     );
     }
     echo json_encode($arr); //返回JSON数据
    }
    
    Copy after login

    jQuery

    We use the powerful jQuery to complete all ajax interactive actions in this example, so the jquery.js library must be loaded first in index.html. Currently, version 1.8 has been released. You can go to the official website http: //jquery.com/Download.
    Then we send an Ajax request to mood.php to obtain the mood list information and display it in the index.html page.

    $(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列表中
      }); 
     }
     }
     });
     ...
    });
    
    Copy after login

    In this way, after we access index.html, the page will load the mood list. Of course, if you want to see the final arrangement effect, you also need CSS. This article does not explain the relevant CSS. Please download the source code or view the demo to learn more.
    Next, we have an interactive action. When the corresponding mood icon is clicked, the icon is marked as published, the height of the histogram changes, and the number above will change to 1, indicating that the publication is successful. If you continue to click the mood icon, it will prompt that it has been published. Once published, it cannot be resubmitted. Please see the code:

    $(".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&#63;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);
     }
     });
    });
    
    
    Copy after login

    If you don’t understand it, you can download the source code and study it carefully. Click the Download button at the beginning of the article to download. Finally, the mysql data table structure required for this example is attached. Thank you for your attention.

    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);
    
    Copy after login

    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template