Home > Web Front-end > JS Tutorial > body text

Ajax and mysql data interaction to create message board function

亚连
Release: 2018-05-22 17:20:00
Original
1780 people have browsed it

This article mainly introduces Ajax and mysql data interaction in detail to realize the message board function. It has certain reference value. Interested friends can refer to it.

I recently made a small The demo implements the data interaction between Ajax and MySQL. The js part uses jq, the backend uses php, and the database is mysql. A node mongodb version will be released later.

I won’t go into details about the use and installation of mysql. I integrate Baidu xampp, Apache server and mysql database by myself, which is very easy to use.

First open the server and database. I first created an "eleven" database here, and then created a table called microblog (please note: I am using a high version of mysql here, and PHP is linked to the database. All methods use mysqli_ If the version is too low, please use the mysql_ method and modify the code yourself)
The following is the code part:

html page and js part:

<!DOCTYPE html> 
<html> 
  <head> 
    <meta charset="UTF-8"> 
    <title>微博留言板</title> 
    <style type="text/css"> 
      *{ 
        margin: 0; 
        padding: 0; 
      } 
      #box{ 
        width: 600px; 
        /*height: 500px;*/ 
        border: 2px solid rgb(85,85,85); 
        border-radius: 15px; 
        margin: 50px auto; 
        padding: 20px 10px 15px; 
        background-color: rgb(85,85,85); 
      } 
      #content{ 
        display: block; 
        resize: none; 
        width: 550px; 
        height: 200px; 
        margin: 0 auto; 
        border: 2px solid rgb(225,225,225); 
        border-radius: 10px; 
        text-align: center; 
        font-size: 30px; 
        background-color: rgb(225,225,225); 
      } 
      #content:focus{ 
        outline: none; 
        border: 2px solid rgb(225,225,225); 
        box-shadow: 0 0 15px rgb(225,225,225); 
      } 
      #btn{ 
        border: 2px solid rgb(255,204,0); 
        width: 80px; 
        height: 40px; 
        border-radius: 5px; 
        margin-top: 30px; 
        font-size: 17px; 
        cursor: pointer; 
        outline: none; 
        background-color: rgb(255,204,0); 
      } 
       
      .list{ 
        list-style: none; 
        background-color: rgb(249,249,249); 
        margin-top: 20px; 
      } 
      .list>li{ 
        padding: 20px 10px 10px; 
        border-bottom: 2px solid rgb(68,68,68); 
        font-size: 20px; 
        color: rgb(200,214,225); 
        position: relative; 
        word-break: break-word; 
        word-wrap: break-word; 
        background-color: rgb(85,85,85); 
         
      } 
      .list>li>.control{ 
        position: absolute; 
        bottom: 3px; 
        right: 5px; 
        font-size: 14px; 
      } 
      .list>li>p{ 
        margin-bottom: 25px; 
      } 
      .control span,.control em{ 
        display: inline-block; 
        margin-right: 15px; 
      } 
      .control em{ 
        color: darkblue; 
        cursor: pointer; 
      } 
      a{ 
        text-decoration: none; 
        color: darkred; 
      } 
      #page>a{ 
        display:inline-block; 
        width: 40px; 
        height: 30px; 
        margin-top: 10px; 
        text-align: center; 
        line-height: 30px; 
        font-size: 20px; 
        border-radius: 5px; 
        color: white; 
        background-color: rgb(51,21,70); 
      } 
      #head{ 
        color: rgb(200,214,225); 
        font-size: 30px; 
        height: 50px; 
        border-bottom: 2px solid rgb(68,68,68); 
        margin-bottom: 20px; 
      } 
    </style> 
  </head> 
  <body> 
    <p id="box"> 
      <p id="head"> 
        留言板 
      </p> 
      <p id="fill_in"> 
        <textarea id="content"></textarea> 
        <button id="btn">提交留言</button> 
      </p> 
      <!--留言列表--> 
      <p id="message_text"> 
        <ul class="list"> 
        </ul> 
      </p> 
      <!--分页--> 
      <p id="page"> 
        <a href="javasript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" >1</a> 
        <a href="javasript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" >2</a> 
      </p> 
    </p> 
  </body> 
  <script src="Jq/jquery-3.1.1.min.js"> 
</html>
Copy after login

Code display Not finished, here is part of the php code.
Continue with part 01, jq’s ajax request:

<script type="text/javascript"> 
    $(function(){ 
      $("#btn").on("click",function(){ 
        if ($("#content").val() == "") { 
          alert("~~客官,说一句再走呗~~"); 
          return; 
        }  
        else{ 
          $.ajax({ 
            type:"get", 
            url:"http://localhost/phpStudy/ajax03/message.php", 
            async:true, 
            dataType:"json", 
            data:{ 
              content:$("#content").val(), 
              act:"add" 
            }, 
            success:function(data){ 
//             var result = JSON.parse(data); 
              if (data.error==0) { 
                createLi(data.id,$("#content").val(),data.time); 
              } else{ 
                alert(data.msg); 
              } 
            } 
          }); 
        } 
         
      }); 
       
      //创建节点 
      function createLi(id,content,time){ 
        var html = $(&#39;<li><p>&#39;+content+&#39;</p><p class="control"><span>时间:&#39;+time+&#39;</span>顶:<em>0</em>踩:<em>0</em><a class="remove" href="javasript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" >删除</a></p></li>&#39;); 
          $(".list").prepend(html); 
          var h = html.height(); 
          html.height(0); 
          html.stop().animate({ 
            height:h 
          },300); 
          //删除 
          html.find(".remove").on("click",function(){ 
            html.stop().animate({ 
              height:0 
            },300,function(){ 
              html.remove(); 
            }) 
          }); 
      } 
    }) 
  </script>
Copy after login

This part is the php code part:

<?php 
  header("Content-type:text/html;charset=utf8"); 
   date_default_timezone_set("PRC"); 
   //链接数据库 
   $link = mysqli_connect("localhost", "root", "", "eleven"); 
   //设置数据库编码格式 
   mysqli_query($link, "set names utf8"); 
?>
Copy after login

Note: I wrote this part as public code because I am learning to do other things is called, so the following code will have

include_once "comment.php";
Copy after login

. This line refers to other codes

0){ 
        $arr = ["error"=>0,"id"=>$insertId,"time"=>$times]; 
        echo json_encode($arr);//将数组转化为json,方便前端使用 
      } 
      else{ 
        $arr = ["error"=>1,"msg"=>"留言失败,请重试!"]; 
        echo json_encode($arr);//将数组转化为json,方便前端使用 
      } 
      break; 
       
    case 'up': 
      $id = $_GET['id']; 
      $search = "SELECT up FROM microblog WHERE id = $id"; 
      $result = mysqli_query($link, $search); 
      $upNum = mysqli_fetch_row($result)[0]; 
      $upNum++; 
      $query = "UPDATE microblog SET up='{$upNum}' WHERE id = '{$id}'"; 
      mysqli_query($link,$query); 
      if(mysqli_affected_rows($link)){//更新数据成功 
        echo '{"error":"0"}'; 
      } 
      else{//更新失败 
        echo '{"error":"1","msg":"点赞失败!"}'; 
      } 
      break; 
       
    case 'down': 
      $id = $_GET['id']; 
      $search = "SELECT down FROM microblog WHERE id = $id"; 
      $result = mysqli_query($link, $search); 
      $downNum = mysqli_fetch_row($result)[0]; 
      $downNum++; 
      $query = "UPDATE microblog SET down='{$downNum}' WHERE id = '{$id}'"; 
      mysqli_query($link,$query); 
      if(mysqli_affected_rows($link)){//更新数据成功 
        echo '{"error":"0"}'; 
      } 
      else{//更新失败 
        echo '{"error":"1","msg":"踩失败!"}'; 
      } 
      break;  
    case 'remove': 
      $id = $_GET['id']; 
      $query ="DELETE FROM microblog WHERE id='{$id}'"; 
      mysqli_query($link,$query); 
      if(mysqli_affected_rows($link)>0){//删除数据成功 
        echo '{"error":"0"}'; 
      } 
      else{ 
        echo '{"error":"1","msg":"删除失败!"}'; 
      } 
      break; 
    case 'count'://返回总页码 
      $query = "SELECT count(id) FROM   microblog"; 
      $result = mysqli_query($link, $query); 
      $count = mysqli_fetch_row($result)[0];//以索引数组形式返回查询结果 
      $countPage = ceil($count/5); 
      echo '{"error":"0","countPage":"'.$countPage.'"}'; 
      break;  
    case 'page'://点击分页或者是页面第一次加载 
      $index = $_GET["num"]*5; 
      $search = "SELECT * FROM microblog ORDER BY id DESC LIMIT {$index},5";//倒叙查询留言 
      $result = mysqli_query($link, $search); 
      $arr = [];//存查询出来的数据 
      while($row = mysqli_fetch_assoc($result)){ 
        array_unshift($arr,$row); 
      } 
//     print_r($arr); 
//     {"error":"0","info":[{},{},{},{},{}]} 
      $resultArr = ["error"=>"0","info"=>$arr]; 
      echo json_encode($resultArr); 
      break; 
     
   } 
?>
Copy after login

. The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Instances of ajax responding to json strings and json arrays (graphic tutorial)

Ajax synchronization and asynchronous issues Brief analysis and solutions

Two methods for Ajax to solve redundant refresh

The above is the detailed content of Ajax and mysql data interaction to create message board function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!