Beego 学习笔记7:JS分页

大憨熊 提交于 2020-04-02 07:31:01

JS分页

1>     JS分页,业务逻辑

(1)     分页采用的是一个叫jquery.pagination.js的一个jquery插件

(2)     需要jquery的支持,此项目中使用到的是jquery-2.1.1.min.js

(3)     分页需要的参数有:记录总数,每页显示个数,页码

(4)     添加搜索的条件,作为查询使用

2>     编写新的model,命名为data.go.其代码如下:

package models 

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

// 用户
type User struct{
	Id              int64    `orm:"auto"`
	Name            string   `orm:"size(100)"`
	Nickname        string   `orm:"size(100)"`
    Pwd             string   `orm:"size(100)"`
    Email           string   `orm:"size(100)"`
    Sex             string   `orm:"size(2)"`
	Roleid          string   `orm:"size(100)"`
	Status          int64    
	Phone           string   `orm:"size(16)"`
}

//根据用户数据总个数
func GetRecordNum(search string) int64 {
	
	o := orm.NewOrm()
	qs := o.QueryTable("user")
	if search !=""{
		qs=qs.Filter("Name",search)
	}
	var us []User
	num, err :=  qs.All(&us)
	if err == nil {
		return num
	}else{
		return 0
	}	
}
func SearchDataList(pagesize,pageno int,search string) (users []User) {
	o := orm.NewOrm()
	qs := o.QueryTable("user")
	if search !=""{
		qs=qs.Filter("Name",search)
	}
	var us []User
	cnt, err :=  qs.Limit(pagesize, (pageno-1)*pagesize).All(&us)
	if err == nil {
		fmt.Println("count", cnt)
	}
	return us
}
//初始化模型
func init() {
	// 需要在init中注册定义的model
	orm.RegisterModel(new(User))
}

  

3>     控制器user.go,其代码如下:

package controllers

import (
	"secondweb/models"
	"fmt"
	"github.com/astaxie/beego"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Get() {
	
	c.TplName = "list.html"
}
func (c *UserController) Post() {
	pageno,err:=c.GetInt("pageno")
	if err!=nil{
       fmt.Println(err)
	}
	search:=c.GetString("search")
	userList:=models.SearchDataList(3,pageno,search)
	listnum:=models.GetRecordNum(search)
	c.Data["json"]=map[string]interface{}{"Count":listnum,"PageSize":3,"Page":pageno,"DataList":userList};
	c.ServeJSON();
}

type YonghuController struct {
	beego.Controller
}
func (c *YonghuController) Post() {
	pageno,err:=c.GetInt("pageno")
	if err!=nil{
       fmt.Println(err)
	}
	search:=c.GetString("search")
	userList:=models.SearchDataList(3,pageno,search)
	listnum:=models.GetRecordNum(search)
	c.Data["json"]=map[string]interface{}{"Count":listnum,"PageSize":3,"Page":pageno,"DataList":userList};
	c.ServeJSON();
}

  

4>     路由配置如下:

package routers

import (
	"secondweb/controllers"
	"github.com/astaxie/beego"
)

func init() {
	beego.Router("/", &controllers.MainController{})
	beego.Router("/Home/PageData", &controllers.UserController{})
	beego.Router("/Home/PageNextData", &controllers.YonghuController{})
}

  

5>     新建一个list.html,其代码如下:

<!DOCTYPE html>
 
<html>
      <head>
        <title>首页 - 用户列表页面</title>
        <link rel="shortcut icon" href="/static/img/favicon.png" />
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <style>
          .am-cf{
            height: 50px;          
            margin-top: 30px;
            line-height: 50px;
            text-align: center;
            vertical-align: middle;
            margin-left: 40%;
          }
          .am-fr{
              float: left;
              line-height: 50px;
              text-align: center;
              vertical-align: middle;
              height: 50px;
              margin-top: -15px;
          }
          .am-pagination{
            list-style:none;
            height: 50px;    
            line-height: 50px;
            text-align: center;
            vertical-align: middle;
          }
          .am-pagination li{
            float:left;
            margin-left: 10px;
          }
          .am-pagination li a{
            text-decoration:none;
          }
          .am-jl{
              float: left;
              margin-left: 20px;
          }
          .am-active{
              color: #f00;
          }
        </style>
      </head>
    
    <body>
     
        <div class="row pull-right" style="margin-bottom: 20px;margin-right: 5px;text-align:right;margin-right: 40px;">
      
          <input type="text" placeholder="请输入名称" id="txt_search"/>
          <button class="" onclick="search()">搜索</button>
        </div>
            
        <table class="table table-striped table-hover table-bordered ">
          <thead>
           <th style="text-align: center">ID</th>
           <th style="text-align: center">名称</th>
           <th style="text-align: center">昵称</th>
           <th style="text-align: center">密码</th>
           <th style="text-align: center">Email</th>
           <th style="text-align: center">性别</th>
           <th style="text-align: center">手机号</th>
         </thead>
        
         <tbody id="sortable">
         </tbody>
        </table> <!--分页部分-->
        <div style="margin: 20px 0px 10px 0;">
         <table style="margin: 0 auto;">
             <tr>
                 <td>
                     <div id="pagination" class="pagination"></div>
                 </td>
             </tr>
         </table>
        </div>
        <script type="text/javascript" src="/static/js/jquery-2.1.1.min.js"></script> 
        <script type="text/javascript" src="/static/js/jquery.paginationNew.js"></script>     
        <script type="text/javascript">
            //页面的初始化
            $(function () {            
              //分页数据
              InitData();
            })
            function search(){
                var search = $("#txt_search").val();//名称
                InitData();
            }
            //使用分页插件pagination分页显示1
        function InitData() {
            var search = $("#txt_search").val();//名称

            $.ajax({
                async: false,
                type: "post",
                url: "/Home/PageData",
                data: {
                    search: search,
                    pageno:0
                },
                success: function (data) {
                    console.log('首页数据')
                    console.log(data)      
                    var Count = data.Count
                    var PageSize = data.PageSize;
                    var Page =data.Page;
                    $("#pagination").pagination(Count, {
                        callback: pageselectCallback,
                        num_edge_entries: 1,
                        prev_text: "上一页",
                        prev_show_always: true,
                        next_text: "下一页",
                        next_show_always: true,
                        items_per_page: PageSize,
                        current_page: Page,
                        link_to: '#__aurl=!/Home/PageData',
                        num_display_entries: 4
                    });
                }
            });
        }

        //使用分页插件分页后的回调函数2
        function pageselectCallback(page_id, jq) {
            var search = $("#txt_search").val();//名称

            $.ajax({
                async: false,
                type: "post",
                url: "/Home/PageNextData",
                data: {
                    search: search,
                    pageno: (parseInt(page_id) + parseInt(1)),
                },
                success: function (data) {
                    console.log('下一页的数据')
                    console.log(data)
                    console.log(data.DataList)
                    htmlData(data.DataList)
                }
            });
        }
        function htmlData(data){
             var html='';
             for(var i=0;i<data.length;i++){
                html+='<tr class="sort-item"  id="module_'+data[i].Id+'" value="'+data[i].Id+'">';  
                html+='   <td style="text-align: center;width: 150px;"><span class="label label-default" >'+data[i].Id+'</span></td>';  
                html+='   <td style="text-align: center;width: 240px;" ><strong>'+data[i].Name+'</strong></td>';  
                html+='   <td style="text-align: center;width: 240px;" ><strong>'+data[i].Nickname+'</strong></td>';  
                html+='   <td style="text-align: center;width: 240px;" ><strong>'+data[i].Pwd+'</strong></td>';  
                html+='   <td style="text-align: center;width: 240px;" ><strong>'+data[i].Email+'</strong></td>';  
                html+='   <td style="text-align: center;width: 240px;" ><strong>'+data[i].Sex+'</strong></td>';  
                html+='   <td style="text-align: center;width: 240px;" ><strong>'+data[i].Phone+'</strong></td>';                     
                html+='</tr>';  
             }
              
             $("#sortable").html(html);
        }
        </script>
    </body>
</html>

  

6>     Main.go的代码如下:

package main

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	_ "secondweb/routers"
	"github.com/astaxie/beego"
)

func init(){
	dbhost := beego.AppConfig.String("dbhost")
    dbport := beego.AppConfig.String("dbport")
    dbuser := beego.AppConfig.String("dbuser")
    dbpassword := beego.AppConfig.String("dbpassword")
    db := beego.AppConfig.String("db")

    //注册mysql Driver
    orm.RegisterDriver("mysql", orm.DRMySQL)
	//构造conn连接
	//用户名:密码@tcp(url地址)/数据库
    conn := dbuser + ":" + dbpassword + "@tcp(" + dbhost + ":" + dbport + ")/" + db + "?charset=utf8"
    //注册数据库连接
    orm.RegisterDataBase("default", "mysql", conn)

    fmt.Printf("数据库连接成功!%s\n", conn)
}
func main() {
    o := orm.NewOrm()
    o.Using("default") // 默认使用 default,你可以指定为其他数据库
    
	beego.Run()
}

  

7>     App.conf配置文件如下:

appname = secondweb
httpport = 9080
runmode = dev

dbhost=192.168.1.87
dbport=3306
dbuser=root
dbpassword=123456
db=test
tablename=user

  

8>     运行起来的效果如下:

 

 

 

 

 

9>     下一章节,讲sql语句

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!