[英]Spray - Parsing forms with checkboxes
I am setting up a simple API part of which accepts POST
requests via form submission. 我正在设置一个简单的API部分,通过表单提交接受POST
请求。 The form requires the user to select one or more checkboxes all sharing the same name eg 该表单要求用户选择一个或多个共享相同名称的复选框,例如
<form>
<input type='text' name='textval'>
<input type='checkbox' name='cbox' value='val1'> Value 1
<input type='checkbox' name='cbox' value='val2'> Value 2
<button type='submit'>Submit</button>
</form>
I am attempting to handle the request in Spray
like so: 我试图在Spray
处理请求,如下所示:
path("mypath") {
post {
formFields('textval, 'cbox) { (textval, cbox) =>
// Now what?
}
}
}
I cannot find documentation in the Spray Docs on how to handle such inputs. 我在Spray Docs中找不到关于如何处理这些输入的文档 。 In fact, this seemed to be an issue that has now been fixed , but I am unsure how to handle this form field with the Spray API 事实上,这似乎是一个现已修复的问题 ,但我不确定如何使用Spray API处理此表单字段
I have found a somewhat hacky solution to meet my needs. 我找到了一个有点hacky解决方案来满足我的需求。 I have changed the names of my checkboxes to represent the values associated with them, and I use optional form fields in my spray route 我更改了复选框的名称以表示与它们关联的值,并且我在喷涂路径中使用可选的表单字段
Here is my new form 这是我的新表格
<form>
<input type='text' name='textval'>
<input type='checkbox' name='cbox1' value='val1'> Value 1
<input type='checkbox' name='cbox2' value='val2'> Value 2
<button type='submit'>Submit</button>
</form>
The route changes accordingly 路线也相应变化
path("mypath") {
post {
formFields('textval, 'cbox1.?, 'cbox2.?) { (textval, cbox1, cbox2) =>
complete(s"textval:'$textval', cbox1:'$cbox1', cbox2:'$cbox2'")
}
}
}
The optional fields get mapped to type Option[String]
which can then be easily checked with .isEmpty
or something similar to determine whether the checkbox was checked. 可选字段被映射到类型Option[String]
,然后可以使用.isEmpty
或类似的东西轻松检查,以确定是否选中了复选框。
However, one issue is that it will allow forms to be posted with no checkboxes selected since they are all optional. 但是,一个问题是它允许发布表单而不选择复选框,因为它们都是可选的。 You could perhaps set one as default. 您也许可以将其设置为默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.