go ajax

作者: 灵山路远 | 来源:发表于2018-01-03 22:37 被阅读0次

    1. 目录结构

    <APP>

          |-- 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.onclick=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

    <!DOCTYPE html>

    <html>    

    <head>

    <script type="text/javascript" src="/static/js/js.js"></script>

    </head>

    <body>

    <div id="myDiv"><h2>use ajax 2</h2></div>

    <button id="butn1" type="button" onclick=loadXMLDoc()>change data </button>

    </body>

    </html>

    相关文章

      网友评论

          本文标题:go ajax

          本文链接:https://www.haomeiwen.com/subject/zvvknxtx.html