フォームフィールドでデータを送信することもできますが、通常はから読み取るだけですresponse.Body
。最小限のjQueryとAppEngineの例を次に示します。
package app
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
)
func init () {
http.HandleFunc("/", home)
http.HandleFunc("/target", target)
}
const homePage =
`<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<form action="/target" id="postToGoHandler">
<input type="submit" value="Post" />
</form>
<div id="result"></div>
<script>
$("#postToGoHandler").submit(function(event) {
event.preventDefault();
$.post("/target", JSON.stringify({"Param1": "Value1"}),
function(data) {
$("#result").empty().append(data);
}
);
});
</script>
</body>
</html>`
func home(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, homePage)
}
type Message struct {
Param1 string
}
func target(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
if body, err := ioutil.ReadAll(r.Body); err != nil {
fmt.Fprintf(w, "Couldn't read request body: %s", err)
} else {
dec := json.NewDecoder(strings.NewReader(string(body)))
var m Message
if err := dec.Decode(&m); err != nil {
fmt.Fprintf(w, "Couldn't decode JSON: %s", err)
} else {
fmt.Fprintf(w, "Value of Param1 is: %s", m.Param1)
}
}
}