duanmei1350 2017-04-25 20:48
浏览 30
已采纳

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

I write simple go web app. In this app, i am sending ajax post request and returning simple "hello world!" string and print it in console, but something is strange. There is three response value in console output. One with empty value and two response with "hello world!" string values. What is wrong with my code?

Golang Code:

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 Code:

(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条回答 默认 最新

  • doushoubu5360 2017-04-25 21:01
    关注

    You need to additionally check the req.readyState:

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

    References:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能