参考:https://studygolang.com/articles/2671
main.go内容
package main
import (
"io"
"net/http"
"text/template"
)
func OnAjax(res http.ResponseWriter, req *http.Request) {
io.WriteString(res, "这是从后台发送的数据")
}
func index(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("index.html") //找模板
t.Execute(w, nil) //执行模板
}
func main() {
http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("js"))))
http.HandleFunc("/", index) //函数也是一种变量
http.HandleFunc("/ajax", OnAjax) //函数也是一种变量
http.ListenAndServe("localhost:8081", nil)
}
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Go语言与ajax示例</title>
<script type="text/javascript" src="js/loli.js"></script>
</head>
<body>
<p><input id="btn1" type="button" value="按钮" /></p>
<p><input id="txt1" type="text" /></p>
</body>
</html>
js文件
window.onload = main;
function main() {
var oBtn = document.getElementById('btn1');
oBtn.onclick = OnButton1;
}
function OnButton1() {
var xhr = new XMLHttpRequest();
xhr.open('get', '/ajax', true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) { // 读取完成
if (xhr.status == 200) {
var oTxt = document.getElementById('txt1');
oTxt.value = xhr.responseText;
}
}
}
}