简体   繁体   English

使用JavaScript动态提交表单-如何精炼代码?

[英]Dynamic form submission using javascript - how to elegant code?

Here is the problem: 这是问题所在:

My page displays a set of items. 我的页面显示了一组项目。 Each item has a check box associated to it (which is part of a form). 每个项目都有一个与其关联的复选框(它是表单的一部分)。 User might check any of these check boxes and press 'Delete' button. 用户可以选中其中任何一个复选框,然后按“删除”按钮。 The same page also has a 'Upload' button which would upload an excel sheet of items. 在同一页面上还具有“上传”按钮,该按钮将上传Excel项目表。 At the moment, my form action sumbits to say : "xyzAction" and I have two different handlers (analogous to Struts Action) - one for deletion of stores and other for uploading stores. 目前,我的表单操作总结为:“ xyzAction”,我有两个不同的处理程序(类似于Struts Action)-一个用于删除商店,另一个用于上载商店。

I am told that the best way to do this is to rely on javascript by doing one of these: 1)) Switching form action on press of upload and delete buttons - there by invoke different actions. 有人告诉我,执行此操作的最佳方法是通过执行以下操作之一来依靠javascript:1)在按上载和删除按钮时切换表单动作-在那里调用不同的动作。 2) Use a hidden variable "act" to set it to delete / upload and submit to a single form. 2)使用隐藏变量“ act”将其设置为删除/上传并提交到单个表单。 The server side action would take care of identifying the act and forwarding to the corresponding action. 服务器端动作将负责识别动作并将其转发到相应动作。

Approach (1) - seems very inelegant to me. 方法(1)-对我来说似乎很优雅。 Playing with form action seems unnecessary. 进行表单动作似乎没有必要。 Approach (2) - would obviously not work if your javascript is turned off and is not very elegant either. 方法(2)-如果您的JavaScript已关闭并且也不是很美观,则显然不起作用。

There must be a third way to doing this?, which would make me happy? 一定有第三种方式可以做到吗?那会让我高兴吗?

听起来您可能需要两种不同的形式才能执行两种不同的操作。

You need to get the HTML correct first. 您需要先正确获取HTML。

You have two different actions, so you should have two forms - a good rule of thumb is that each form should only have one submit button. 您有两种不同的操作,因此您应该有两种形式-一个好的经验法则是,每种形式都应该只有一个提交按钮。 This is the best practice for HTML and will ensure that the page works without JS or any other trickery. 这是HTML的最佳做法,可确保该页面在没有JS或其他任何欺骗的情况下都能正常运行。

Once you have the page working like this, use JS to manipulate the DOM to produce the UI that you need. 使页面像这样工作后,请使用JS来操作DOM以生成所需的UI。 This is using JS to add behvour to the UI and is best practice for unobtrusive JS. 这是使用JS向用户界面添加行为,这是不打扰JS的最佳实践。

(If you really want to conflate your actions in a single form, changing the action of the form with JS is the best course of action. But consider what would happen if a user checks a check box and then changes their mind and uploads a file leaving the checkbox checked. You should take care that this shouldn't delete anything.) (如果您确实想将动作合并为一种形式,则最好用JS更改表单的动作。但是请考虑一下,如果用户选中一个复选框然后改变主意并上传文件,会发生什么情况保持选中该复选框。您应注意不要删除任何内容。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM