dongxiong2000 2016-03-27 09:53
浏览 111
已采纳

如何使用Jquery和golang中的输入json数据进行Ajax调用?

I am trying to make an ajax call in Jquery but I am getting empty response. But when I try to do the same through curl I am succeeding. Here is my JS,

time = new Date($.now());
requestJSON = '{"Method":"GET","AppName":"Proline","ServiceURL":"http://localhost:8081/api/services/tags/","Properties":null,"Object":"","Timestamp":"'+time+'"}'
$.ajax({
  type: "GET",
  url: "http://localhost:8081/api/services/tags/",
  // The key needs to match your method's input parameter (case-sensitive).
  data: requestJSON,
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(data){alert(data);},
  failure: function(errMsg) {
      alert(errMsg);
  }
});

I also tried dataType: "jsonp" but no luck.

And the curl command is here,

curl --data '{"Method":"GET","AppName":"Proline","ServiceURL":"http://localhost:8081/api/services/tags/","Properties":null,"Object":"","Timestamp":"2016:03:27 00:08:11"}'
-X GET http://localhost:8081/api/services/tags/

I have the server code in golang. I already set the header to Access-Control-Allow-Headers:*. Here is my server handler.

 func tagsHandler(w http.ResponseWriter, r *http.Request, extra []string) {
    if origin := r.Header.Get("Origin"); origin != "" {
            w.Header().Set("Access-Control-Allow-Origin", origin)
            w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
            w.Header().Set("Access-Control-Allow-Headers",
                    "*")
    }
    // Stop here if its Preflighted OPTIONS request
    if r.Method == "OPTIONS" {
            return
    }
    var response []byte
    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        log.Printf("FATAL IO reader issue %s ", err.Error())
    }
    log.Printf("Body : %s ", string(body))
    method    := r.Method
    log.Printf("tagsHandler() :: service method %s ", method)
    if method == HTTP_VERB_POST {
                response = tagslogic.PostTag(body)
    } else if method == HTTP_VERB_GET {
                response = tagslogic.GetTags(body)
    } else if method == HTTP_VERB_PUT {
                response = tagslogic.PutTag(body)
    } else if method == HTTP_VERB_DEL {
            response = tagslogic.DelTag(body)
        }
    w.Write(response)
}

To be specific I am getting empty request body in server side. could someone help me with this?

  • 写回答

2条回答 默认 最新

  • doufenyu7610 2016-03-27 13:39
    关注

    The issue was the call is not sending the request data in body [But somehow curl works fine]. When I try to get the body, err := ioutil.ReadAll(r.Body) it gave empty value. So I changed to get from r.Form

    r.ParseForm()
    var body []byte
    for key, _ := range r.Form {
        body = []byte(key)
        break
    }
    

    r.Form gives a map. So I am iterating through the map and getting the req data. This SO post gave the solution. May be helpful to others :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!