在节点中形成元素数组键并表达 [英] form element array keys in node and express

查看:39
本文介绍了在节点中形成元素数组键并表达的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管我尽了最大的努力,但我仍然坚持将表单元素的数组键提交给NodeJS和Express以及把手.

Despite my best efforts I'm stuck on getting the array keys for form elements submitted to NodeJS and Express and handlebars.

我的表单元素如下:

{{#each block}}
<input type='text' name='block_payout[{{id}}]' />
{{/each}

这会在浏览器中产生以下标记:

This results in the following markup in the browser:

<input type='text' name='block_payout[14]' />
<input type='text' name='block_payout[15]' />
<input type='text' name='block_payout[16]' />

在PHP中,这将导致一个数组作为$ _POST数组的元素:

In PHP this would result in an array as an element of the $_POST array:

$_POST [
  block_payout [
    14 => value1
    15 => value2
    16 => value3
  ]
]

但是,Node/Express中的req.body属性删除了这些键并创建了一个索引数组:

However, the req.body property in Node/Express removes these keys and creates an indexed array:

req.body [
  block_payout [
    0 => value1
    1 => value2
    2 => value3
  ]
]

因为我想使用密钥将提交的值绑定到其他东西,所以这对我来说是个大问题.有谁知道我如何才能使用正确的键获取提交的表单数据?

Since I want to use the key to tie the submitted values to something else this is a big problem for me. Does anyone know how I can get the submitted form data with the correct keys??

推荐答案

似乎正文解析器仅在看到数字键时使用一个数组(必须从索引0开始),而在看到至少一个数字键时使用一个对象.非数字键.考虑到这一点,您可以尝试以下方法之一:

It seems like the body parser uses an array (which must start at index 0) when it sees only numeric keys, and an object when there is at least one key that is non-numeric. With that in mind, you could try one of the following methods:

  1. 使用隐藏的表单输入来强制在数组上使用对象.示例:

  1. Use a hidden form input to force the use of an object over an array. Example:

<input type='hidden' name='block_payout[null]' />
<input type='text' name='block_payout[14]' />
...

结果显示为以下正文:

{ block_payout: { '14': 'test1', '15': 'test2', '16': 'test3', null: '' } }

  • 使用非数字字符为键添加前缀以强制对象映射.示例:

  • Prefix your keys with a non-numeric character to force the object mapping. Example:

    <input type='text' name='block_payout[i14]' />
    ...
    

    结果显示为以下正文:

    { block_payout: { i14: 'test1', i15: 'test2', i16: 'test3' } }
    

  • 这篇关于在节点中形成元素数组键并表达的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆