gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:58:04 26 4
gpt4 key购买 nike

我编写了简单的 go web 应用程序。在这个应用程序中,我发送 ajax post 请求并返回简单的“hello world!”字符串并在控制台中打印出来,但有些奇怪。控制台输出中有三个响应值。一个是空值,两个是“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

最佳答案

您需要额外检查req.readyState:

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

引用资料:

关于Golang - Web 应用程序中的多个响应值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43620664/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com