解决 go iris ReadJSON 无法获取 json,并提示 unexpected end of JSON input 的错误
前台页面使用 jquery 往后台传值时iris报 unexpected end of JSON input。
后台代码
func Update(ctx iris.Context){
type nodes struct {
Id string `json:"id" form:"id"`
Name string `json:"name" form:"name"`
}
var data []nodes
if err := ctx.ReadJSON(&data); err != nil {
ctx.JSON(iris.Map{
"status": "error",
"message": err,
})
}else{
//TODO CURD
ctx.JSON(iris.Map{
"status": "ok",
"message": "操作成功",
})
}
}
前台 jquery
var data = [
{id:"1",name:"沈恩忍"},
{id:"2",name:"王佑春"},
{id:"3",name:"沈子民"},
{id:"4",name:"王诗涵"},
];
$.ajax({
url:"localhost:8080/update",
type:'post',
dataType:'json',
data:JSON.stringify(data),
success : function(r){
if (r.status == "ok") {
alert("成功执行")
}else{
alert("执行失败")
}
}
})
浏览器传的值,如下图:

解决方法
在 jquery ajax 中添加 contentType: "application/json; charset=utf-8" 即可,如下代码
$.ajax({
url:"localhost:8080/update",
type:'post',
dataType:'json',
contentType: "application/json; charset=utf-8",//此句非常重要
data:JSON.stringify(data),
success : function(r){
if (r.status == "ok") {
alert("成功执行")
}else{
alert("执行失败")
}
}
})
浙公网安备 33010602011771号