go gin传json,参数string int float bool

go gin传json,参数string int float bool,第1张

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)
type Test struct{
	Name string `json:"name" binding:"required"`
	Intval int32 `json:"intval" binding:"required"`
	Floatval float32 `json:"floatval"`
	BoolVal bool `json:"boolval"`
}

func main() {
	var r=gin.Default()


	r.POST("ask",func(c *gin.Context){
		json:=Test{}
		err:=c.BindJSON(&json)
		if err!=nil{
			fmt.Println(err)
		}
		fmt.Println(json)
		fmt.Println(json.Intval+10)
		c.JSON(http.StatusOK,gin.H{
			"result":"success",
		})
	})
	r.LoadHTMLGlob("test.html")
	r.GET("index",func(c *gin.Context){
		c.HTML(http.StatusOK,"test.html",gin.H{})
	})



	r.Run(":8090")

}

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <link rel="stylesheet" href="https://cdn.acwing.com/static/jquery-ui-dist/jquery-ui.min.css">
    <script src="https://cdn.acwing.com/static/jquery/js/jquery-3.3.1.min.js">script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js">script>
head>
<body>
    <button class="test">
        test
    button>
    <script>
        $(document).ready(function (){
            $(".test").click(


                function (){
                    console.log(
                        JSON.stringify({
                            name:"test",
                            intval:123,
                            floatval:1.11,
                        })
                    )

                    $.ajax({
                        url:"http://localhost:8090/ask",
                        type:'post',
                        dataType:'json',
                        contentType: "application/json",
                        data:JSON.stringify({
                            name:"test",
                            intval:123,
                            floatval:1.11,
                            boolval:true,
                        }),
                        success:function(resp){

                        }
                    });

                }
            )
        })
    script>
body>
html>

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/941060.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-17
下一篇 2022-05-17

发表评论

登录后才能评论

评论列表(0条)

保存