如何在Jquery和Golang中使用输入的JSON数据进行Ajax调用?

huangapple go评论103阅读模式
英文:

How to make ajax call with input json data in Jquery and golang?

问题

我正在尝试在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)
}

具体来说,我在服务器端得到的是空请求体。有人能帮我解决这个问题吗?

英文:

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?

答案1

得分: 0

你的数据已经在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);
  }
});
英文:

Your data is already stringified in 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

得分: 0

问题是调用没有在请求体中发送请求数据[但是某种方式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返回一个映射。所以我遍历映射并获取请求数据。这个SO帖子给出了解决方案。可能对其他人有帮助 如何在Jquery和Golang中使用输入的JSON数据进行Ajax调用?

英文:

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 如何在Jquery和Golang中使用输入的JSON数据进行Ajax调用?

huangapple
  • 本文由 发表于 2016年3月27日 17:53:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/36246010.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定