为什么我不能用ajax获得responseText

时间:2014-02-21 07:54:54

标签: javascript ajax go

我想做一些像ajax注册的事情。我只是使用ajax request 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();
}

})();

1 个答案:

答案 0 :(得分:1)

问题出现在你的Get() Javascript函数中:

Get = function (url,cb){
    request.open("GET",url);
    request.onreadystatechange = cb(request);
    request.send();
}

您正在将onreadystatechange属性设置为调用cb的结果。此时,请求尚未发送,因此没有要读取的响应文本。以下是解决问题的一种可能方法:

request.onreadystatechange = function() { cb(request); };