前台頁面使用 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("執行失敗") } } })