2016-11-20 53 views
-2

我使用AJAX这样的数据发送到golang应用:如何使用golang解析POST AJAX数据?

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

postform=map[------WebKitFormBoundarytZ4Y8wFVKpWBWBnu 
Content-Disposition: form-data:[] name:["data" 

sdfsdf 
------WebKitFormBoundarytZ4Y8wFVKpWBWBnu-- 
]] 
------------ 

编辑

发现的problem.The问题是FORMDATA发送数据curl -H 'Content-type: application/x-www-form-urlencoded' --data $'------WebKitFormBoundaryiVVK2EjSLDbqaccx\r\nContent-Disposition: form-data; name="data"\r\n\r\nsdfsdf\r\n------WebKitFormBoundaryiVVK2EjSLDbqaccx--\r\n' --compressed

,而不是`卷曲--data“数据= sdfsdf”

现在,真正的问题是如何如何得到FORMDATA发送正常数据?

回答

0

您可以使用FormValue方法表格http.Request对象访问HTTP POST数据。我假设你的r*http.Request对象。那么你应该可以通过r.FormValue("data")访问你的data。例如:

var myVariable string 
myVariable = r.FormValue("data") 

文档: Go-Lang net/http

+0

不起作用。仍然将“后”价值减半。 –

0

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

// Delete this line 
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 

我无法找到这个特定的官方说法,但如果你在所有的各种FORMDATA看()的演示,他们没有设置请求的内容类型。无论如何,它使用“multipart/form-data”。

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