解決 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("執行失敗")
		}
	}
})

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM