gin: 静态文件

一,下载jquery

官网:

https://jquery.com/

从命令行下载:

$ wget https://code.jquery.com/jquery-3.7.1.min.js

二,代码:

目录结构

image

routes

package routes

import (
	"github.com/gin-gonic/gin"
	"mediabank/controller"
)

func Routes() *gin.Engine {
	router := gin.Default()

	//指定静态目录
	router.Static("/static", "./static")

	// 1. 加载模板文件
	router.LoadHTMLGlob("templates/**/*.html")

	//media
	media := controller.NewMediaController()
	mediaGroup := router.Group("/media")
	{
		mediaGroup.GET("/detail", media.Detail)
		mediaGroup.GET("/list", media.List)
		mediaGroup.GET("/user", media.User)
	}

	return router
}

controller

package controller

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

type MediaController struct{}

func NewMediaController() MediaController {
	return MediaController{}
}

//得到详情
func (ic *MediaController) User(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"name": "老王",
		})
}

//得到详情
func (ic *MediaController) Detail(c *gin.Context) {
	c.HTML(200, "detail.html", gin.H{
		"Title": "Gin 模板示例",
		"Message": "欢迎来到 Gin 的世界!",
	})
}

//得到列表
func (ic *MediaController) List(c *gin.Context) {
	var data = gin.H{
		"Title": "Gin 列表示例",
		"Message": "欢迎来到Gin 列表!",
	}
	c.HTML(200, "list.html", data)
}

css

body {
    font-family: Arial, sans-serif;
    background-color: #f5f5f5;
}

detail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ .Title }}</title>
    <link rel="stylesheet" href="/static/css/global.css">
    <script src="/static/js/jquery-3.7.1.min.js"></script>
</head>
<body>
<h1>{{ .Message }}</h1>
<button onclick="getName()">获取当前用户名字</button>
<script>
    function getName() {
        var paramsData = {
            a:1,
            b:2
        }
        var url = "/media/user";
        $.ajax({
            type: 'GET',
            url: url,
            data: paramsData,
            dataType: 'json',
            success: function(data) {

                console.log("成功");
                console.log(data);
                if (data.hasOwnProperty('name')) {
                    alert('name:'+data.name)
                } else {
                    alert('数据获取失败')
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log("失败");

                console.error('Error: ' + textStatus + ' - ' + errorThrown);
            }
        });
    }

</script>
</body>
</html>

三,测试效果

image

posted @ 2025-09-20 09:46  刘宏缔的架构森林  阅读(13)  评论(0)    收藏  举报