简体   繁体   English

使用JQuery访问表单元素值的“正确”方法

[英]“Correct” Way to Access Form Element Values with JQuery

As anybody who has written javascript/jquery knows, there's a lot of different ways to do the same thing. 任何编写javascript / jquery的人都知道,有很多不同的方法可以做同样的事情。 I'm currently trying to send some data to the server on form submit and as an AJAX request, and I was wondering what the "correct" way of doing this was. 我正在尝试在表单提交和AJAX请求中向服务器发送一些数据,我想知道这样做的“正确”方法是什么。

I was tentatively going to just access all the form elements by ID and then pull their values, but I know you can also iterate through them. 我暂时只是通过ID访问所有表单元素然后提取它们的值,但我知道你也可以遍历它们。 What is typically done in this situation? 在这种情况下通常做什么?

If you have inputs and selects in your form, you can just serialize the data. 如果您在表单中有输入和选择,则可以序列化数据。

$( "input, select" ).serialize();

you can iterate over the fields and then populate the object. 您可以迭代字段然后填充对象。 but what happens if you have many fields in your form. 但是如果表单中有很多字段会发生什么。 It's leads to lots of extra code when you have a method that abstracts all this. 当你有一个抽象所有这些的方法时,它会导致许多额外的代码。

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

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