What is the expected order of an array submitted in an HTML form?

99封情书 提交于 2020-01-21 10:43:07

问题


I'm wondering if there is any sort of guarantee on the order of POST variables I will see on the server side.

My use case is I have a form that a user will fill out to enter a list of names and emails. I'm using a table rows, each of which has two inputs:

<table>
<tr>
<td><input type='text' name='name[]' /></td>
<td><input type='text' name='email[]' /></td>
</tr>
<tr>
<td><input type='text' name='name[]' /></td>
<td><input type='text' name='email[]' /></td>
</tr>
</table>

The row might be cloned via javascript to allow the user to type in more names and emails so I won't know ahead of time how many will be submitted.

On the server side, I see $_POST['email'] and $_POST['name'] set but I am wondering if I can safely assume $_POST['email'][0] will correspond to $_POST['name'][0], $_POST['email'][1] will correspond to $_POST['name'][1], and so on. Some basic testing seem to indicate yes but I'm wondering if there is a guarantee or if I'm just getting lucky.


回答1:


why not add a grouping key like:

<td><input type='text' name='user[0][name]' /></td>
<td><input type='text' name='user[0][email]' /></td>
</tr>
<tr>
<td><input type='text' name='user[1][name]' /></td>
<td><input type='text' name='user[1][email]' /></td>

and then manuall set the user indexes when you clone based on the current number. This way everything is already coallated.




回答2:


What is the expected order of an array submitted in an HTML form?

According to the HTML specification:

The control names/values are listed in the order they appear in the document

http://www.w3.org/TR/html401/interact/forms.html#form-content-type

However, it's better coding practice to employ an indexed array approach as shown in prodigitalson's answer.




回答3:


Data will appear in same order like in form. So first row have key 0, second row - 1.




回答4:


As Vaidas Zilionis said, data will appear in exact the same order as they appear in the form, see the W3C's HTML 4.01 Specification:

application/x-www-form-urlencoded
[...] 2. The control names/values are listed in the order they appear in the document.

multipart/form-data
[...] A "multipart/form-data" message contains a series of parts, each representing a successful control. The parts are sent to the processing agent in the same order the corresponding controls appear in the document stream.



来源:https://stackoverflow.com/questions/3712481/what-is-the-expected-order-of-an-array-submitted-in-an-html-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!