doukui9491
2014-02-21 07:54
浏览 187

为什么我无法使用Ajax获取responseText

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条回答 默认 最新

  • duandi6531 2014-02-21 12:55
    已采纳

    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); };
    
    点赞 评论

相关推荐 更多相似问题