목표 : 1. Html 데이터를 Ajax로 사용해 go Handler로 값 전달
2. 전달받은 값으로 DB api 조회(url)
router.go
server.route.POST("/sendToGo", handler.ReceiveData)
main.html
<head>
<title>메인 페이지</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
<input name="search" type="text" id="search" value="1" >
<input type="button" onclick="sendToGo()" value="전송" >
</body>
<script>
function sendToGo(){
var formSerializeArray = $('#search').serializeArray();
//json 가공
//[{ name : "a", value : "1" }] to {"a":"1"}
var params = {};
for (var i = 0; i < formSerializeArray.length; i++){
params[formSerializeArray[i]['name']] = formSerializeArray[i]['value'];
}
alert(JSON.stringify(params));
//{"search":"1"}
$.ajax({
type : 'post',
url : '/sendToGo',
data : JSON.stringify(params),
error: function(){
alert("에러발생");
},
success : function(json){
alert(json)
}
});
}
</script>
main.go
type Board struct {
ID int `json:"ID"`
Title string `json:"Title"`
Content string `json:"Content"`
}
func ReceiveData(c *gin.Context) {
//json형태로 값을 받음
data, _ := c.GetRawData()
reqBody := value{}
//json을 decode
err := json.Unmarshal([]byte(data), &reqBody)
if err != nil {
fmt.Println(err.Error())
return
}
//decode한 값을 바탕으로 url 전송
resp, _ := http.Get("http://localhost/posts/" + reqBody.Search)
//받은 데이터 전부 읽기
respBody, _ := ioutil.ReadAll(resp.Body)
var data1 Board
json.Unmarshal([]byte(respBody), &data1)
c.JSON(200, data1)
}
}
'GoLang' 카테고리의 다른 글
JqGrid post (0) | 2020.11.30 |
---|---|
GIN Ajax table 조작 (0) | 2020.11.25 |
GIN 동적 그래프 그리기 (0) | 2020.11.20 |
GIN 그래프 그리기 (0) | 2020.11.19 |
GIN MongoDB Test (0) | 2020.11.17 |