Spray - 解析带有复选框的表单
Spray - Parsing forms with checkboxes
我正在设置一个简单的 API 部分,其中一部分通过表单提交接受 POST
请求。该表单要求用户 select 一个或多个共享相同名称的复选框,例如
<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>
我正在尝试像这样处理 Spray
中的请求:
path("mypath") {
post {
formFields('textval, 'cbox) { (textval, cbox) =>
// Now what?
}
}
}
我在 Spray Docs on how to handle such inputs. In fact, this seemed to be an issue that has now been fixed 中找不到文档,但我不确定如何使用 Spray API
处理此表单字段
我找到了一个有点老套的解决方案来满足我的需要。我更改了复选框的名称以表示与它们关联的值,并且我在喷涂路线中使用了可选的表单字段
这是我的新表格
<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>
路线相应改变
path("mypath") {
post {
formFields('textval, 'cbox1.?, 'cbox2.?) { (textval, cbox1, cbox2) =>
complete(s"textval:'$textval', cbox1:'$cbox1', cbox2:'$cbox2'")
}
}
}
可选字段被映射到 Option[String]
类型,然后可以使用 .isEmpty
或类似的东西轻松检查以确定复选框是否被选中。
但是,一个问题是它允许在不选中复选框的情况下发布表单,因为它们都是可选的。您或许可以将其中一个设置为默认值。
我正在设置一个简单的 API 部分,其中一部分通过表单提交接受 POST
请求。该表单要求用户 select 一个或多个共享相同名称的复选框,例如
<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>
我正在尝试像这样处理 Spray
中的请求:
path("mypath") {
post {
formFields('textval, 'cbox) { (textval, cbox) =>
// Now what?
}
}
}
我在 Spray Docs on how to handle such inputs. In fact, this seemed to be an issue that has now been fixed 中找不到文档,但我不确定如何使用 Spray API
处理此表单字段我找到了一个有点老套的解决方案来满足我的需要。我更改了复选框的名称以表示与它们关联的值,并且我在喷涂路线中使用了可选的表单字段
这是我的新表格
<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>
路线相应改变
path("mypath") {
post {
formFields('textval, 'cbox1.?, 'cbox2.?) { (textval, cbox1, cbox2) =>
complete(s"textval:'$textval', cbox1:'$cbox1', cbox2:'$cbox2'")
}
}
}
可选字段被映射到 Option[String]
类型,然后可以使用 .isEmpty
或类似的东西轻松检查以确定复选框是否被选中。
但是,一个问题是它允许在不选中复选框的情况下发布表单,因为它们都是可选的。您或许可以将其中一个设置为默认值。