go+ajax实现简单的信息增删改查的交互页面

预览
 

技术栈

后端:go(gin+gorm);前端:html,css,javascript(jquery+ajax);数据库:MySQL

项目结构

(红框标出来的不重要)

自己的一些记录与理解:
controller文件夹:接口层,用户访问请求时对接
dao文件夹:data access object 数据访问对象,封装对数据库的访问,不涉及业务逻辑
models文件夹:存放项目使用到的数据的抽象,定义数据

代码部分:

前端关键代码(index.html):
 

/* 
更新表格
    */
function updateInfo(data) {
    $("#tb-body").empty()
    $.each(data, function (index, item) {
        let row =
            '<tr><td style="display:none">' +
            item.id + "</td><td>" +
            item.username + "</td><td>" +
            item.psd + "</td><td>" +
            item.role + "</td><td>" +
            "<button onclick='edit(this)'>修改</button>" +
            "<button onclick='del(this)'>删除</button>" +
            "</td></tr>";
        $("#tb-body").append(row);
    })
}
/* 
加载信息
    */
function loadInfo() {
    $.ajax({
        url: "/info",
        dataType: 'json',
        type: 'get',
        success: function (data) {
            console.log(data);
            updateInfo(data)
        },
        error: function (err) {
            console.log(err);
        }
    })
}
/* 
新增
    */
function add() {
    // event.preventDefault();
    let data = {};
    let value = $('#info-form').serializeArray();
    $.each(value, function (index, item) {
        data[item.name] = item.value;
    });
    let json = JSON.stringify(data);
    console.log(json);
    $.ajax({
        url: "/info",
        data: json,
        contentType: 'application/json',
        type: 'post',
        success: function (data) {
            //清空表单
            loadInfo()// 重新加载表单
            updateInfo(data) // 更新表格
            $('#info-form').get(0).reset();//转换为dom元素调用reset方法
        },
        error: function (err) {
            console.log(err);
        }
    })
}
/* 
删除
    */
function del(val) {
    // 获取id值 √
    let value = $(val).parent().parent().find("td")
    let id = value.eq(idNum).text();
    // 传回id值 √
    $.ajax({
        url: "/info/" + id,
        type: "delete",
        success: function (data) {
            loadInfo();// 重新获取信息
            updateInfo(data); // 更新表格
        },
        error: function (err) {
            console.log(err);
        }
    })
}
/* 
获取需要修改的信息
    */
function edit(val) {
    let info = [];
    $(val).parent().parent().children().each((i, item) => {
        console.log("index", i, "item", $(item).text());
        info.push($(item).text())
    }); // 获取数据
    info = info.slice(0, -1); // 去掉按钮文本                
    $("#edit-form input").each((i, item) => {
        $(item).val(info[i + 1])
    })// 绑定数据
    singleID = info[idNum];// 保存id
    show();// 显示表单
}
/* 
更新
    */
function update() {
    let newInfoVal = $("#edit-form").serializeArray();
    let newInfo = {}
    $.each(newInfoVal, (i, item) => {
        newInfo[item.name] = item.value
    })
    newInfo = JSON.stringify(newInfo)
    $.ajax({
        url: "/info/" + singleID,
        type: "put",
        data: newInfo,
        contentType: 'application/json',
        success: (res) => {
            console.log(res);
            cancel()// 隐藏表单
            loadInfo()// 重新加载表单
            updateInfo(res) // 更新表格
        },
        error: (err) => {
            console.log(err);
        }
    })

}

后端关键代码:

main.go:
func main() {
	// 连接数据库
	err := dao.InitMySQL()
	if err != nil {
		fmt.Printf("init mysql failed, err:%v\n", err)
		return
	}
	// 模型绑定
	dao.DB.AutoMigrate(&models.Info{})
	r := gin.Default()
	r.LoadHTMLFiles("index.html")
	r.GET("/index", controller.IndexHandler)         // 连接
	r.GET("/info", controller.GetInfoHandler)        // 获取信息
	r.POST("/info", controller.AddInfoHandler)       // 添加信息
	r.PUT("/info/:id", controller.EditInfoHandler)   // 修改信息
	r.DELETE("/info/:id", controller.DelInfoHandler) // 修改信息
	r.Run(":9090")
}
controller/controller.go
func IndexHandler(c *gin.Context) {
	c.HTML(http.StatusOK, "index.html", gin.H{"name": "lzmy"})
}

func GetInfoHandler(c *gin.Context) {
	infos, err := models.GetInfo()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"error:": err,
		})
	} else {
		c.JSON(http.StatusOK, infos)
	}
}

func AddInfoHandler(c *gin.Context) {
	var info models.Info
	c.BindJSON(&info)
	err := models.AddInfo(&info)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
	} else {
		c.JSON(http.StatusOK, info)
	}
}

func EditInfoHandler(c *gin.Context) {
	var info models.Info
	id, ok := c.Params.Get("id")
	c.BindJSON(&info)
	fmt.Printf("%v\n", info)
	if ok {
		models.EditInfo(id, &info)
	} else {
		c.JSON(http.StatusOK, gin.H{
			"msg": "更新失败",
		})
	}
}

func DelInfoHandler(c *gin.Context) {
	fmt.Println("成功")
	id, ok := c.Params.Get("id")
	if ok {
		models.DelInfo(id)
	} else {
		c.JSON(http.StatusOK, gin.H{
			"msg": "删除失败",
		})
	}
}
dao/mysql.go
func InitMySQL() (err error) {
	dsn := "root:root@tcp(127.0.0.1:3306)/own?charset=utf8mb4&parseTime=True&loc=Local"
	// 不能用:=模糊定义,会在代码块创建一个独立的变量,无法传递到外面
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		return
	}
	return
}
models/info.go
type Info struct {
	ID       int    `json:"id"`
	Username string `json:"username"`
	Psd      string `json:"psd"`
	Role     string `json:"role"`
}

func AddInfo(info *Info) (err error) {
	err = dao.DB.Create(&info).Error
	return
}

func GetInfo() (infos []*Info, err error) {
	if err = dao.DB.Find(&infos).Error; err != nil {
		return nil, err
	}
	return // 裸返回
}

func EditInfo(id string, info *Info) (err error) {
	err = dao.DB.Where("id = ?", id).Updates(info).Error
	return
}

func DelInfo(id string) (err error) {
	err = dao.DB.Delete(&Info{}, id).Error
	return
}

是看了B站七米的goWeb教程后写的第一个算是全栈的项目,也是第一次接触后端,有不足的地方请多指正,谢谢

完整代码可以去我的码云或者github上看,欢迎star

项目地址

https://gitee.com/lzmy03/first-go-projecthttps://gitee.com/lzmy03/first-go-project

https://github.com/Artifity/first-go-projecthttps://github.com/Artifity/first-go-project

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值