5

如果不使用 JavaScript,设计和处理一个用户可以添加任意数量的新输入字段的表单是非常乏味的。

目前我正在执行以下操作:在表单中使用两个不同的提交按钮,一个用于添加新输入字段,一个用于提交导致数据库请求的表单。

  • 使用的方法是POST

    为了添加新的输入字段,我想使用GET但由于一种形式的两种方法是不可能的,我必须在 POST 请求中进行。

  • 为一种类型的输入字段进行此操作相当容易,但是当您需要为子表单(同一表单中的某些输入字段组)执行此操作时,这不仅变得乏味,而且容易出错

我不满意,是否有更智能的方法来实现这一点,而无需开始编写大量处理代码并进行重定向,或者至少简化实现以降低错误风险!

此外,也许Java提供了一个解决方案来解决这个一般优雅的问题,因为我使用的是Java Servlets

打开 JavaScript 后,我​​会提供一个单独的解决方案,我只关心后备解决方案,这不是正常情况。

4

1 回答 1

2

See, working without JavaScript severely restrict your abilities: you have to rely upon the standard HTTP request/response cycle. In other words, you have to rebuild a new page (adding some input field) and send this new page each time - there's no workarounds.

Here's how I would implement it:

<form action="/path/to/action" method="post">
  <input name="param_a" />
  <input name="param_b" />
  <button type="submit" name="next_input" value="param_c">Add a field</button>
  <button type="submit" name="submit">Submit your form</button>
</form>

... then within the server-side code I'd just check whether next_input param is sent or not. If sent, its value will be used to get the control which is to be added - and give the corresponding value (param_d, for example) to the next next_input.

UPDATE: but I just can't help wondering is this really necessary. Usually we design for 'No JS' cases when these pages are typical landing pages (scanned by search robots). Thinking about some users that will go to your page without JS enabled, yet willing to use it with all pretty things enabled... well, it's not very cost-effective, to say the least. )

于 2012-07-08T19:54:54.600 回答