doukui9491 2014-02-21 07:54
浏览 199
已采纳

为什么我无法使用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); };
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!