Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

javascript - 如何使用JavaScript / jQuery获取表单数据?(How can I get form data with JavaScript/jQuery?)

Is there a simple, one-line way to get the data of a form as it would be if it was to be submitted in the classic HTML-only way?(是否有一种简单的单行方式来获取表单数据,就像以经典的纯HTML方式提交那样?)

For example:(例如:) <form> <input type="radio" name="foo" value="1" checked="checked" /> <input type="radio" name="foo" value="0" /> <input name="bar" value="xxx" /> <select name="this"> <option value="hi" selected="selected">Hi</option> <option value="ho">Ho</option> </form> Output:(输出:) { "foo": "1", "bar": "xxx", "this": "hi" } Something like this is too simple, since it does not (correctly) include textareas, selects, radio buttons and checkboxes:(这样的事情太简单了,因为它不(正确地)包含文本区域,选择,单选按钮和复选框:) $("#form input").each(function () { data[theFieldName] = theFieldValue; });   ask by Bart van Heukelom translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use $('form').serializeArray() , which returns an array :(使用$('form').serializeArray() ,它返回一个数组 :)

[ {"name":"foo","value":"1"}, {"name":"bar","value":"xxx"}, {"name":"this","value":"hi"} ] Other option is $('form').serialize() , which returns a string :(另一个选项是$('form').serialize() ,它返回一个字符串 :) "foo=1&bar=xxx&this=hi" Take a look at this jsfiddle demo(看看这个jsfiddle演示)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...