动态创建和提交表单
Dynamically create and submit a form
我的模型中有一些数据,我想将其放入请求正文中并通过 POST 请求发送。问题是我希望浏览器导航到请求 URL,因为路由 returns 是一个新的 HTML 页面。一般情况下,将数据放在一个表单中,然后使用 JS 提交即可。
如何使用 Elm 执行此操作?
编辑 - 根据您的评论说明更新
据我了解你的问题,你希望能够在幕后构造一个 POST 请求,但让浏览器 post 它以便浏览器被重定向到它所在的实际页面posted,留下你的 Elm 应用程序。
您可以在 Elm 中构建表单,但将其隐藏,然后当您想要触发它时,将表单 ID 传递到执行表单提交的端口。
type alias Model =
{ foo : String }
view model =
div []
[ Html.form
[ id "my-form"
, action "https://requestb.in/1crya751"
, method "POST"
, style [ ( "display", "none" ) ]
]
[ input [ type_ "text", name "foo", value model.foo ] []
]
, div []
[ button [ onClick SubmitForm ] [ text "Submit" ] ]
]
type Msg
= SubmitForm
update msg model =
case msg of
SubmitForm ->
model ! [ submitForm "my-form" ]
port submitForm : String -> Cmd msg
您的 javascript 可能看起来像这样(尽管在 id 不存在的情况下进行了一些错误处理):
var app = Elm.Main.fullscreen()
app.ports.submitForm.subscribe(function(formId) {
document.getElementById(formId).submit();
});
这里是working example of this on ellie-app.com. It posts the form to requestb.in so you can see what has been posted by going here.
我推荐隐藏表单而不是尝试使用标准 Http
包的原因是因为听起来您希望浏览器重定向到您正在 posting 的任何表单到。你无法通过使用 Http
包真正实现同样的事情。
我的模型中有一些数据,我想将其放入请求正文中并通过 POST 请求发送。问题是我希望浏览器导航到请求 URL,因为路由 returns 是一个新的 HTML 页面。一般情况下,将数据放在一个表单中,然后使用 JS 提交即可。
如何使用 Elm 执行此操作?
编辑 - 根据您的评论说明更新
据我了解你的问题,你希望能够在幕后构造一个 POST 请求,但让浏览器 post 它以便浏览器被重定向到它所在的实际页面posted,留下你的 Elm 应用程序。
您可以在 Elm 中构建表单,但将其隐藏,然后当您想要触发它时,将表单 ID 传递到执行表单提交的端口。
type alias Model =
{ foo : String }
view model =
div []
[ Html.form
[ id "my-form"
, action "https://requestb.in/1crya751"
, method "POST"
, style [ ( "display", "none" ) ]
]
[ input [ type_ "text", name "foo", value model.foo ] []
]
, div []
[ button [ onClick SubmitForm ] [ text "Submit" ] ]
]
type Msg
= SubmitForm
update msg model =
case msg of
SubmitForm ->
model ! [ submitForm "my-form" ]
port submitForm : String -> Cmd msg
您的 javascript 可能看起来像这样(尽管在 id 不存在的情况下进行了一些错误处理):
var app = Elm.Main.fullscreen()
app.ports.submitForm.subscribe(function(formId) {
document.getElementById(formId).submit();
});
这里是working example of this on ellie-app.com. It posts the form to requestb.in so you can see what has been posted by going here.
我推荐隐藏表单而不是尝试使用标准 Http
包的原因是因为听起来您希望浏览器重定向到您正在 posting 的任何表单到。你无法通过使用 Http
包真正实现同样的事情。