Javascript 如何使用golang解析POST AJAX数据?

Javascript 如何使用golang解析POST AJAX数据?,javascript,ajax,Javascript,Ajax,我使用ajax将数据发送到golang应用程序,如下所示: httpRequest = new XMLHttpRequest(); if (!httpRequest) { document.getElementById("errorArea").innerText = "Giving up :( Cannot create an XMLHTTP instance'"; } url = "http://127.0.0.1:8080/putContent?url="+windo

我使用ajax将数据发送到golang应用程序,如下所示:

 httpRequest = new XMLHttpRequest();
 if (!httpRequest) {
     document.getElementById("errorArea").innerText = "Giving up :( Cannot create an XMLHTTP instance'";
  }

url =  "http://127.0.0.1:8080/putContent?url="+window.location.pathname;

httpRequest.onreadystatechange = sendContents;
httpRequest.open('POST', url);
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

var fd = new FormData();
fd.set ("data",document.getElementById("ta").value);
httpRequest.send(fd);
r.ParseForm()
fmt.Print("postform=")
fmt.Println(r.PostForm)
后端是这样的:

 httpRequest = new XMLHttpRequest();
 if (!httpRequest) {
     document.getElementById("errorArea").innerText = "Giving up :( Cannot create an XMLHTTP instance'";
  }

url =  "http://127.0.0.1:8080/putContent?url="+window.location.pathname;

httpRequest.onreadystatechange = sendContents;
httpRequest.open('POST', url);
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

var fd = new FormData();
fd.set ("data",document.getElementById("ta").value);
httpRequest.send(fd);
r.ParseForm()
fmt.Print("postform=")
fmt.Println(r.PostForm)
结果(将sdfsdf键入textarea ta):

编辑

发现问题。问题是FormData以
curl-H'内容类型发送数据:application/x-www-form-urlencoded'--data$'--WebKitFormBoundaryiVVK2EjSLDbqaccx\r\n内容处置:表单数据;name=“data”\r\n\r\nsdfsdf\r\n------webkitformboundaryivk2ejsldbqaccx--\r\n'-压缩

而不是'curl--data“data=sdfsdf”


现在,真正的问题是如何让FormData发送普通数据?

您可以使用
FormValue
方法表单
HTTP.Request
对象访问HTTP POST数据。我假设您的
r
*http.Request
对象。然后您应该能够使用
r.FormValue(“数据”)
访问您的
数据。例如:

var myVariable string
myVariable = r.FormValue("data")
文件:

尽量不要在JS中设置请求内容类型。显然,浏览器在发送FormData()对象时会自动执行此操作

我找不到关于此的特定官方声明,但是如果您查看所有的FormData()演示,没有一个设置请求内容类型。在任何情况下,它都使用“多部分/表单数据”


在我的Go服务器上,典型的Go r.ParseForm()和解码器在初始测试中似乎运行良好。

不起作用。仍然将“post”值一分为二。