1. 目录结构
|-- main.go
|-- template
|--index.html
|--public
|-- js
|-- js.js
共有三个文件main.go ,index.html和js.js。 template和public/js都为目录。
2. main.go
package main
import (
"fmt"
"html/template"
"io"
"net/http"
)
func main() {
mux := http.NewServeMux()
files := http.FileServer(http.Dir("./public"))
mux.Handle("/static/", http.StripPrefix("/static/", files))
mux.HandleFunc("/", index)
mux.HandleFunc("/onAjax", onAjax)
server := &http.Server{
Addr: "0.0.0.0:8080",
Handler: mux,
}
server.ListenAndServe()
fmt.Println("it is finished")
}
func index(w http.ResponseWriter, r *http.Request) {
fmt.Println("in Index")
t, err := template.ParseFiles("template/index.html")
if err != nil {
fmt.Println(err)
return
}
err = t.Execute(w, nil)
}
func onAjax(w http.ResponseWriter, r *http.Request) {
fmt.Println("in onAjax")
io.WriteString(w, "this is from home")
}
3 js.js
//window.onload = main;
//function main(){
//var oBtn = document.getElementById("butn1");
//oBtn.οnclick=loadXMLDoc();
//}
function loadXMLDoc()
{
var xmlhttp;
xmlhttp= new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4 && xmlhttp.status == 200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/onAjax",true);
xmlhttp.send();
}
4 index.html
use ajax 2
change data