将数据以multipart/form-data的形式发布,采用MVVC/AngularJS的方式。

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

Posting data as multipart/form-data the MVVC/AngularJS way

问题

我正在使用AngularJS开发前端,使用Go开发后端的web应用程序,我正在尝试使用multipart/form-data编码的数据进行POST请求,而不是URL编码。我尝试过在Google上搜索,但似乎找不到一个不假设我只是尝试上传文件的示例。我只是想要POST一个简单的表单,其中包含一些文本字段,没有文件。

我可以通过绕过Angular,使用一个简单的HTML表单来实现method="POST",但在JavaScript中实现这一点似乎非常困难。

在服务器端,我使用http.Request.FormValue("key")来解码POST请求。

有人可以指点我正确的方向吗?谢谢!

英文:

I am developing a webapp using AngularJS for the frontend (still very new to JS) and Go for the backend and I am stumped trying to POST multipart/form-data encoded data instead of URL encoded. I have tried to google it, but I cannot seem to find an example that doesn't assume that I'm only trying to upload a file. I am simply trying to POST a simple form with some text fields and no files.

I can get it work by bypassing Angular with a simple html form using method="POST", but it is surprisingly difficult to do in javascript.

On the server side, I am decoding the POST request with http.Request.FormValue("key").

Could someone point me in the right direction? Cheers!

答案1

得分: 1

这里有一个方法可以调用表单元素的submit()函数(这里使用jQuery):

$('#yourForm').submit();

当然,这需要表单所指向的端点能够处理“完整的浏览器重定向”并进行正确的重定向。

也许更好的解决方案是(因为你同时控制前端和后端),让Angular应用程序提交JSON数据(默认方式),然后在后端进行处理。

英文:

There is always the posibility to invoke the submit() of the form element (using jQuery here):

$('#yourForm').submit();

This will (of course) require that the endpoint targeted by the form handle the "full browser rollby" - and redirect properly.

It might be a better solution (since you control both frontend and backend) to have the Angular application submit JSON (as it defaults) and just handle that on the backend.

huangapple
  • 本文由 发表于 2014年7月15日 15:55:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/24752811.html
匿名

发表评论

匿名网友

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

确定