Answer the question
In order to leave comments, you need to log in
How to kick data from Golang back to Js via AJAX?
Not so long ago, I began to storm Go. And while chirping with an AJAX request, I stumbled upon a problem. At the root, I have, as you might guess, index markup with Jquery AJAX.
<body>
<button id="send">Send</button>
</body>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script>
var data;
$('#send').click(function() {
$.ajax({
url: "http://localhost:8080/receive",
method: "POST",
data : { sendedData: 'Hello'},
success : function(data) {
alert(data);
},
});
});
</script>
package main
import (
"fmt"
"net/http"
)
func swap(a,b string) (string,string) {
return b, a
}
func receiveAjax(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
sendedData := r.FormValue("sendedData")
fmt.Println("My request is: ", sendedData)
a, b := swap(sendedData, "World")
fmt.Println(a, b)
}
}
func main() {
http.HandleFunc("/receive", receiveAjax)
http.ListenAndServe(":8080", nil)
}
Answer the question
In order to leave comments, you need to log in
Two minutes of googling:
// AJAX Request Handler
func ajaxHandler(w http.ResponseWriter, r *http.Request) {
//parse request to struct
var d Data
err := json.NewDecoder(r.Body).Decode(&d)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// create json response from struct
a, err := json.Marshal(d)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
w.Write(a)
}
w.Write(a)
.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question