jQuery serializeArray() 键值对
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11376184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery serializeArray() key value pairs
提问by Akshat
I'm having a bit of trouble serializing a form
我在序列化表单时遇到了一些麻烦
<form>
<input type="text" name="name1" value="value1"/>
<input type="text" name="name2" value="value2"/>
</form>
$(form).serializeArray()
Will return [{name:"name1",value:"value1"},{name:"name2",value:"value2"}]
pairs.
将返回[{name:"name1",value:"value1"},{name:"name2",value:"value2"}]
对。
Is it possible to get output in the form
是否可以以表格形式获得输出
{name1:value1,name2:value2}
So that they are easier to handle?
以便它们更容易处理?
回答by Darin Dimitrov
var result = { };
$.each($('form').serializeArray(), function() {
result[this.name] = this.value;
});
// at this stage the result object will look as expected so you could use it
alert('name1 = ' + result.name1 + ', name2 = ' + result.name2);
回答by Luka Govedi?
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
回答by Hollister
The accepted answer works great if your form doesn't have checkboxes or radio buttons. Since groups of those all have the same name attribute, you need to create an array value inside the object. So for html like:
如果您的表单没有复选框或单选按钮,则接受的答案效果很好。由于这些组都具有相同的 name 属性,因此您需要在对象内创建一个数组值。所以对于 html 像:
<input type="checkbox" value="1" name="the-checkbox">
<input type="checkbox" value="1" name="the-checkbox">
<input type="checkbox" value="1" name="the-checkbox">
You'll get:
你会得到:
{the-checkbox:['1', '2', '3']}
Thisbit of code handles everything nicely.
这段代码可以很好地处理一切。
/*!
* jQuery serializeObject - v0.2 - 1/20/2010
* http://benalman.com/projects/jquery-misc-plugins/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
// Whereas .serializeArray() serializes a form into an array, .serializeObject()
// serializes a form into an (arguably more useful) object.
(function($,undefined){
'$:nomunge'; // Used by YUI compressor.
$.fn.serializeObject = function(){
var obj = {};
$.each( this.serializeArray(), function(i,o){
var n = o.name,
v = o.value;
obj[n] = obj[n] === undefined ? v
: $.isArray( obj[n] ) ? obj[n].concat( v )
: [ obj[n], v ];
});
return obj;
};
})(jQuery);
Usage
用法
$(form).serializeObject();
回答by Erez Rabih
new_obj = {}
$.each($(form).serializeArray(), function(i, obj) { new_obj[obj.name] = obj.value })
your data is in new_obj
您的数据在 new_obj 中
回答by Mr. Mak
You can make a custom function.
您可以创建自定义函数。
var complex = $(form).serialize(); // name1=value1&name2=value2
var json = toSimpleJson(complex); // {"name1":"value1", "name2":"value2"}
function toSimpleJson(serializedData) {
var ar1 = serializedData.split("&");
var json = "{";
for (var i = 0; i<ar1.length; i++) {
var ar2 = ar1[i].split("=");
json += i > 0 ? ", " : "";
json += "\"" + ar2[0] + "\" : ";
json += "\"" + (ar2.length < 2 ? "" : ar2[1]) + "\"";
}
json += "}";
return json;
}
回答by Vitaliy Maschenko
Here is some modernization of Hollister's code.
这是Hollister代码的一些现代化。
(function($,undefined){
'$:nomunge'; // Used by YUI compressor.
$.fn.serializeObject = function(){
var obj = {},
names = {};
$.each( this.serializeArray(), function(i,o){
var n = o.name,
v = o.value;
if ( n.includes( '[]' ) ) {
names.n = !names.n ? 1 : names.n+1;
var indx = names.n - 1;
n = n.replace( '[]', '[' + indx + ']' );
}
obj[n] = obj[n] === undefined ? v
: $.isArray( obj[n] ) ? obj[n].concat( v )
: [ obj[n], v ];
});
return obj;
};
})(jQuery);
In case you need field names as myvar[]
for checkboxes.
如果您需要字段名称作为myvar[]
复选框。
回答by Tina
Give your form an id(form-id)
给你的表单一个 id(form-id)
var jsoNform = $("#form-id").serializeObject();
jQuery.fn.serializeObject = function () {
var formData = {};
var formArray = this.serializeArray();
for (var i = 0, n = formArray.length; i < n; ++i)
formData[formArray[i].name] = formArray[i].value;
return formData;
};
回答by Gregory Bologna
To get only form inputs where has a value...
要仅获取具有值的表单输入...
var criteria = $(this).find('input, select').filter(function () {
return ((!!this.value) && (!!this.name));
}).serializeArray();
criteria: {name: "LastName", value: "smith"}
标准:{名称:“姓氏”,值:“史密斯”}
回答by Lukas Labryszewski
Here is my solution which supports radio buttons and multi-select.
这是我的解决方案,它支持单选按钮和多选。
var data = $('#my_form').serializeArray().reduce(function (newData, item) {
// Treat Arrays
if (item.name.substring(item.name.length - 2) === '[]') {
var key = item.name.substring(0, item.name.length);
if(typeof(newData[key]) === 'undefined') {
newData[key] = [];
}
newData[key].push(item.value);
} else {
newData[item.name] = item.value;
}
return newData;
}, {});
console.log(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my_form">
<select name="muli_select[]" multiple="multiple">
<option value="1" selected>Value 1</option>
<option value="2" selected>Value 2</option>
<option value="3">Value 3 Not selected</option>
</select>
<br>
<input name="my_text" type="hidden" value="Hidden Text"/>
<input name="my_text2" type="text" value="Shown Text"/>
<br>
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female
</form>
回答by Nick Parsons
You can do this quite simply using .reduce()
and destructuring assignment:
你可以很简单地使用.reduce()
和解构赋值来做到这一点:
const arr = $('form').serializeArray(); // get the array
const data = arr.reduce((acc, {name, value}) => ({...acc, [name]: value}),{}); // form the object
Example:
例子:
$('form').on('submit', function(e) {
e.preventDefault(); // only used for example (so you can see output in console);
const arr = $(this).serializeArray(); // get the array
const data = arr.reduce((acc, {name, value}) => ({...acc, [name]: value}),{}); // form the object
console.log(data);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" placeholder="username" name="username"/>
<input type="email" placeholder="email" name="email"/>
<input type="submit" />
</form>