为什么我无法通过Ajax获取responseText?

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

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

    &lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot;               &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
	&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
	&lt;head&gt;
	&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
	&lt;title&gt;{{.Title}}&lt;/title&gt;
	&lt;style type=&quot;text/css&quot;&gt;
	input {
		display: inline-block;
		background: rgba(45,45,45,.03);
	}
	form {
		text-align: center;
		width: 200px;
		margin: auto;
	}
	.container {
		margin-top: 120px;
	}
	&lt;/style&gt;
	&lt;/head&gt;

	&lt;body&gt;
	&lt;div class=&quot;container&quot;&gt;
	  &lt;form method=&quot;post&quot; action=&quot;/regist&quot;&gt;
	    &lt;input type=&quot;text&quot; name=&quot;username&quot; placeholder=&quot;账号&quot;/&gt;
	    &lt;input type=&quot;password&quot; name=&quot;password&quot; placeholder=&quot;密码&quot; /&gt;
	    &lt;button&gt;sign me in&lt;/button&gt;
	  &lt;/form&gt;
	&lt;/div&gt;
	&lt;script type=&quot;text/javascript&quot; src=&quot;../assets/ajax.js&quot;&gt;&lt;/script&gt; 
	&lt;script type=&quot;text/javascript&quot;&gt;


	function cb(request){
	  alert(&quot;Server is done!&quot;)
	  console.log(request.responseText)
	  var res = request.responseText
	  //var resJSON = JSON.parse(res)
	  //console.log(res)
	  alert(res)
	}

	Get(&quot;http://127.0.0.1:3000/check&quot;,cb)

	&lt;/script&gt;
	&lt;/body&gt;
	&lt;/html&gt;

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(&quot;key:&quot;, k)
			fmt.Println(&quot;value&quot;, v)
		}
		fmt.Fprintf(w, &quot;{userId:1}&quot;)
	}
	func Register(w http.ResponseWriter, r *http.Request) {

		if r.Method == &quot;GET&quot; {
			fmt.Println(&quot;GET&quot;,r.URL.Path)
			t, err := template.ParseFiles(&quot;templates/regist.gtpl&quot;)

			if err != nil {
				panic(err)
			}
			//长度,容量
			//studentsandstates := make(studentsAndStateSlice,20)
			
			t.Execute(w, Render{Title:&quot;注册&quot;})
		}
	}

	func init() {
		staticHandler = http.StripPrefix(&quot;/assets/&quot;, http.FileServer(http.Dir(&quot;statics&quot;)))
	}

	func main() {
		http.HandleFunc(&quot;/check&quot;, sayHelloName)
		http.HandleFunc(&quot;/register&quot;, Register)
		//已经有静态文件了
		http.HandleFunc(&quot;/assets/&quot;, StaticServer)
		err := http.ListenAndServe(&quot;:3000&quot;, nil)
		if err != nil {
			log.Fatal(&quot;ListenAndServe: &quot;, err)
		}
	}

in my ajax.js

var Get

(function(){var request = false

function createRequest() {

  try {
    request = new XMLHttpRequest();
  } catch (trymicrosoft) {
    //两种微软的XMLHttpRequest
    try {
      request = new ActiveXObject(&quot;Msxml2.XMLHTTP&quot;);
    } catch (othermicrosoft) {
      try {
        request = new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);
      } catch (failed) {
        request = false;
      }
    }
  }
  if (!request)
    alert(&quot;Error initializing XMLHttpRequest!&quot;);
}

createRequest();

Get = function (url,cb){
	request.open(&quot;GET&quot;,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(&quot;GET&quot;,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); };

huangapple
  • 本文由 发表于 2014年2月21日 15:54:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/21928482.html
匿名

发表评论

匿名网友

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

确定