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

如何使用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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵