在Web应用程序中,Golang支持多个响应值。

huangapple go评论151阅读模式
英文:

Golang - multiple response values in web app

问题

我写了一个简单的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);
		}
	};
}());

你的代码看起来没有明显的问题。可能是因为你的浏览器在发送请求时会产生额外的日志输出。你可以尝试在控制台输出之前添加一些条件判断,以确保只输出一次响应。例如:

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

		req.onreadystatechange = function () {
			if (req.readyState === 4 && req.status === 200) {
				console.log(req.responseText);
			}
		}
	};
}());

这样可以确保只在收到有效响应时输出日志。希望这可以解决你的问题。

英文:

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);
	   }
   };
}());

在Web应用程序中,Golang支持多个响应值。
在Web应用程序中,Golang支持多个响应值。

答案1

得分: 3

你需要额外检查req.readyState

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

参考资料:

英文:

You need to additionally check the req.readyState:

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

References:

huangapple
  • 本文由 发表于 2017年4月26日 04:48:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/43620664.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定