Beego中给前端ajax传递json数据
1.定义一个传递给ajax的json数据的容器,如:
resp := make(map[string]interface{})
2.给容器赋值,如:
resp["errno"] = 1
resp["errmsg"] = "获取电话号码错误"
3.把容器传递给前端
this.Data["json"] = resp
4.指定传递方式
this.ServeJSON()
注:3中定义成this.Data["json"]
的原因“
查看ServeJSON()的源码:
// ServeJSON sends a json response with encoding charset.
func (c *Controller) ServeJSON(encoding ...bool) {
var (
hasIndent = true
hasEncoding = false
)
if BConfig.RunMode == PROD {
hasIndent = false
}
if len(encoding) > 0 && encoding[0] {
hasEncoding = true
}
c.Ctx.Output.JSON(c.Data["json"], hasIndent, hasEncoding)
}
可以看出回发一个json用的就是c.Data["json"]
格式,会把Data中key为"json"的value回发给前端ajax