【问题标题】:How to make ajax call with input json data in Jquery and golang?如何使用 Jquery 和 golang 中的输入 json 数据进行 ajax 调用?
【发布时间】:2016-03-27 09:53:28
【问题描述】:

我正在尝试在 Jquery 中进行 ajax 调用,但得到的响应是空的。但是当我尝试通过 curl 做同样的事情时,我成功了。这是我的 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);
  }
});

我也试过dataType: "jsonp",但没有运气。

而curl命令就在这里,

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/

我在 golang 中有服务器代码。我已经将标题设置为Access-Control-Allow-Headers:*。这是我的服务器处理程序。

 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)
}

具体来说,我在服务器端收到了空的请求正文。 有人可以帮我解决这个问题吗?

【问题讨论】:

  • 我认为你不需要字符串化,你实际上是在字符串化2次
  • 就像@Mir 说的,requestJSON 已经是一个字符串了
  • @slash197 - 我尝试不使用 JSON.stringify 但它没有帮助:( .
  • @slash197 - 我更新了问题,因为它重定向到 JSON.stringify 问题。我将 JSON.stringify(requestJSON) 更改为 requestJSON。
  • @DineshAppavoo 来自您的更新代码,您需要 stringfy

标签: jquery json ajax curl go


【解决方案1】:

您的数据已经在 console.log 中字符串化

 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/",
      data:JSON.stringify(requestJSON),
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(data){alert(data);},
      failure: function(errMsg) {
          alert(errMsg);
      }
    });

【讨论】:

    【解决方案2】:

    问题是调用没有在正文中发送请求数据 [但不知何故 curl 工作正常]。当我尝试获取 body, err := ioutil.ReadAll(r.Body) 时,它给出了空值。于是我改为从r.Form获取

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

    r.Form 给出了一张地图。所以我正在遍历地图并获取 req 数据。这个SO post 给出了解决方案。可能对其他人有帮助:)

    【讨论】:

      猜你喜欢
      • 2021-07-21
      • 1970-01-01
      • 2012-10-14
      • 2016-01-26
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多