Golang - Web应用程序中的多个响应值

时间:2017-04-25 20:48:37

标签: go

我写简单的go web app。在这个应用程序中,我发送ajax post请求并返回简单的" hello world!"字符串并在控制台中打印,但有些奇怪。控制台输出中有三个响应值。一个空值,两个响应"你好世界!"字符串值。我的代码出了什么问题?

Golang代码:

package main

import (
    "io"
    "net/http"
    "html/template"
)

func main() {
     http.HandleFunc("/ajax", ajaxHandler)
     http.HandleFunc("/script.js", srcHandler)
     http.HandleFunc("/", mainHandler)
     http.ListenAndServe(":8080", nil)
}

func mainHandler(w http.ResponseWriter, r *http.Request) {
    t, err := template.ParseFiles("home.html")
    if err != nil {
        http.Error(w, http.StatusText(500), 500)
        return
    }

    err = t.Execute(w, nil)
    if err != nil {
        http.Error(w, http.StatusText(500), 500)
        return
    }
}

func srcHandler(w http.ResponseWriter, r *http.Request) {
     http.ServeFile(w, r, "script.js")
}

func ajaxHandler(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Hello World!")
}

Javascript代码:

(function () {
    window.onclick = function () {
        var req = new XMLHttpRequest();
        req.open("post", "/ajax", true);
        req.send();

        req.onreadystatechange = function () {
            console.log(req.responseText);
       }
   };
}());

enter image description here enter image description here

1 个答案:

答案 0 :(得分:3)

您还需要另外检查req.readyState

   req.onreadystatechange = function () {
        if (req.readyState === XMLHttpRequest.DONE) {
            console.log(req.responseText);
        }
   }

参考文献: