英文:
why can i not get responseText with ajax
问题
我想要做一个类似于使用Ajax注册的功能。我只是使用Ajax请求URL "/check",它返回"{success:1}",但是当我使用res = request.responseText时,res是空的。然而,当我使用console.log(request.responseText)时,它显示为*{success:1}*。我该如何获取这个值?我的代码有什么问题?
在我的regist.gtpl文件中:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{{.Title}}</title>
<style type="text/css">
input {
display: inline-block;
background: rgba(45,45,45,.03);
}
form {
text-align: center;
width: 200px;
margin: auto;
}
.container {
margin-top: 120px;
}
</style>
</head>
<body>
<div class="container">
<form method="post" action="/regist">
<input type="text" name="username" placeholder="账号"/>
<input type="password" name="password" placeholder="密码" />
<button>sign me in</button>
</form>
</div>
<script type="text/javascript" src="../assets/ajax.js"></script>
<script type="text/javascript">
function cb(request){
alert("Server is done!")
console.log(request.responseText)
var res = request.responseText
//var resJSON = JSON.parse(res)
//console.log(res)
alert(res)
}
Get("http://127.0.0.1:3000/check",cb)
</script>
</body>
</html>
在我的main.go文件中:
func sayHelloName(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
fmt.Println(r.Form)
for k, v := range r.Form {
fmt.Println("key:", k)
fmt.Println("value", v)
}
fmt.Fprintf(w, "{userId:1}")
}
func Register(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
fmt.Println("GET",r.URL.Path)
t, err := template.ParseFiles("templates/regist.gtpl")
if err != nil {
panic(err)
}
//长度,容量
//studentsandstates := make(studentsAndStateSlice,20)
t.Execute(w, Render{Title:"注册"})
}
}
func init() {
staticHandler = http.StripPrefix("/assets/", http.FileServer(http.Dir("statics")))
}
func main() {
http.HandleFunc("/check", sayHelloName)
http.HandleFunc("/register", Register)
//已经有静态文件了
http.HandleFunc("/assets/", StaticServer)
err := http.ListenAndServe(":3000", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
在我的ajax.js文件中:
var Get
(function(){var request = false
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
//两种微软的XMLHttpRequest
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
}
createRequest();
Get = function (url,cb){
request.open("GET",url);
request.onreadystatechange = cb(request);
request.send();
}
})();
以上是你要翻译的内容。
英文:
i wanna do something like regist with ajax. i just use ajax request url "/check",and it returns "{success:1}",but when i use res = request.responseText, res is nothing.however,i console.log(request.responseText),it turns {success:1},how can i get the value, what's wrong whith my code?
in my regist.gtpl
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{{.Title}}</title>
<style type="text/css">
input {
display: inline-block;
background: rgba(45,45,45,.03);
}
form {
text-align: center;
width: 200px;
margin: auto;
}
.container {
margin-top: 120px;
}
</style>
</head>
<body>
<div class="container">
<form method="post" action="/regist">
<input type="text" name="username" placeholder="账号"/>
<input type="password" name="password" placeholder="密码" />
<button>sign me in</button>
</form>
</div>
<script type="text/javascript" src="../assets/ajax.js"></script>
<script type="text/javascript">
function cb(request){
alert("Server is done!")
console.log(request.responseText)
var res = request.responseText
//var resJSON = JSON.parse(res)
//console.log(res)
alert(res)
}
Get("http://127.0.0.1:3000/check",cb)
</script>
</body>
</html>
in my main.go
func sayHelloName(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
fmt.Println(r.Form)
for k, v := range r.Form {
fmt.Println("key:", k)
fmt.Println("value", v)
}
fmt.Fprintf(w, "{userId:1}")
}
func Register(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
fmt.Println("GET",r.URL.Path)
t, err := template.ParseFiles("templates/regist.gtpl")
if err != nil {
panic(err)
}
//长度,容量
//studentsandstates := make(studentsAndStateSlice,20)
t.Execute(w, Render{Title:"注册"})
}
}
func init() {
staticHandler = http.StripPrefix("/assets/", http.FileServer(http.Dir("statics")))
}
func main() {
http.HandleFunc("/check", sayHelloName)
http.HandleFunc("/register", Register)
//已经有静态文件了
http.HandleFunc("/assets/", StaticServer)
err := http.ListenAndServe(":3000", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
in my ajax.js
var Get
(function(){var request = false
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
//两种微软的XMLHttpRequest
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
}
createRequest();
Get = function (url,cb){
request.open("GET",url);
request.onreadystatechange = cb(request);
request.send();
}
})();
答案1
得分: 1
看起来问题出在你的 Get()
JavaScript 函数中:
Get = function (url, cb){
request.open("GET", url);
request.onreadystatechange = cb(request);
request.send();
}
你将 onreadystatechange
属性设置为调用 cb
的结果。此时,请求尚未发送,因此没有响应文本可供读取。下面是解决问题的一种可能方式:
request.onreadystatechange = function() { cb(request); };
英文:
It looks like the problem is in your Get()
Javascript function:
Get = function (url,cb){
request.open("GET",url);
request.onreadystatechange = cb(request);
request.send();
}
You are setting the onreadystatechange
property to the result of calling cb
. At this point, the request has not been sent, so there is no response text to read. Below is one possible way to solve the problem:
request.onreadystatechange = function() { cb(request); };
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论