Gin渲染html代码,
参考文档:https://www.kancloud.cn/shuangdeyu/gin_book/949436
后端代码:
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
//文档: https://www.kancloud.cn/shuangdeyu/gin_book/949436
func main() {
router := gin.Default()
router.LoadHTMLGlob("templates/*")
//router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
router.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{
"title": "Main website",
})
return
})
type requestDataModel struct {
Name string `json:"name"`
Pass int `json:"pass"`
Age int `json:"age"`
}
router.POST("/getData", func(c *gin.Context) {
fmt.Print(c.PostForm("name"))
var requestData requestDataModel
if err := c.BindJSON(&requestData); err == nil {
}
c.JSON(http.StatusOK, gin.H{
"code": 200,
"msg": "success",
"data": requestData,
})
return
})
// http://127.0.0.1:8080/index
router.Run()
}
templates/index.html 代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<style>
.spanstyle {
color: red
}
</style>
<body>
<span class="spanstyle">测试渲染效果</span>
</body>
</html>
<script type="text/javascript">
$(function () {
$.ajax({
url: '/getData',// 跳转到 action
data: {
"name": "zhangsan",
"pass": 123456,
"age": 1
},
type: 'post',
contentType: 'application/json',
dataType: "json",
success: function (data) {
if (data.msg == "true") {
alert("修改成功!");
window.location.reload();
}
},
error: function (res, err) {
//console.log(res);
}
});
})
</script>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。