Home > Web Front-end > JS Tutorial > Ajax+mysql creates message board function

Ajax+mysql creates message board function

php中世界最好的语言
Release: 2018-04-02 14:58:10
Original
1937 people have browsed it

This time I will bring you the function of making a message board with Ajax+mysql. What are the precautions for making a message board with Ajax+mysql? The following is a practical case, let's take a look.

Recently I made a small demo to realize the data interaction between Ajax and MySQL. The js part uses jq, the backend uses php, and the database is mysql. I will make a node+mongodb version 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 = $('<li><p>'+content+'</p><p class="control"><span>时间:'+time+'</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>'); 
          $(".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

<?php 
  /* 
   * 开发文档 
   * 1.用于提交的留言留言进行存储 
   * url:http://localhost/phpStudy/ajax03/message.php 
   * 提交方式:get 
   * 提交参数说明: 
   * content 必须 留言板内容 
   * act 必须 借口标识 
   * 返回参数说明 
   * 成功:{"error":"0","id":1,"time":"2016-11-30"} 
   * 失败:{"error":1,"msg":"留言失败,请重试"} 
   * 
   * 2.up 
   * id 必须 留言的id编号 
   * act 必须 接口标识 up 
   * 返回声明 
   * 成功:{"error":"0"} 
   * 失败:{"error":"1","msg":"点赞失败"} 
   * 
   * 3.分页(获取页码的接口); 
   * act 必须 接口标识 count 
   * 返回参数说明: 
   * 成功:{"error":"0","countPage":"3"}; 
   * 失败:{"error":"1","msg":"请求数据失败,请重试!"} 
   * 
   * 4.分页(点击页码跳转) 
   * url:http://localhost/phpStudy/ajax03/message.php 
   * 提交方式:get 
   * 提交参数说明: 
   * starPage 必须参数 页码索引值 
   * act 必须 接口标识 page 
   * 返回参数说明 
   * 成功:{"error":"0","data":[{},{},{},{},{}]} 
   * 失败:{"error":"1","msg":"数据查询失败,请重试!"} 
   * 
   */ 
   include_once "comment.php"; 
   $act = $_GET["act"];//接口请求标识 
   switch ($act) { 
    case &#39;add&#39;://提交留言 
      $content = $_GET["content"]; 
      $time = time(); 
      $times = date("Y-m-d H:i:s",$time); 
      $query = "INSERT INTO microblog(id,content,time) VALUES(null,&#39;{$content}&#39;,&#39;{$times}&#39;)"; 
      mysqli_query($link,$query); 
      $insertId = mysqli_insert_id($link); 
      if($insertId>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

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other php Chinese websites related articles!

Recommended reading:

What is the difference between synchronization and asynchronous implementation using Ajax

AJAX cross-domain request JSONP to obtain JSON data Detailed explanation of steps (with code)

The above is the detailed content of Ajax+mysql creates 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