我想知道如何转换当前发送的数据(使用serializeArray()
)
data[0][name]:title
data[0][value]:This is my sample title
data[1][name]:description
data[1][value]:This is an (optional) description but I'm filling it out as an example
data[2][name]:source
data[2][value]:http://www.cnn.com
data[3][name]:category
data[3][value]:animals
改为这样发送:
data[title]:This is my sample title
data[description:This is an (optional) description but I'm filling it out as an example
data[source]:http://www.cnn.com
data[category]:animals
代码:
$(function() {
$('input[type="submit"]').click(function() {
var $data = $('#js-serialize').serializeArray();
console.log($data);
$.post('/echo/json', {
'data': $data
}, function(data) {
console.log(data);
}, 'json');
return false;
});
});
<form id="js-serialize">
<input name="title" placeholder="title" />
<input name="description" placeholder="description" />
<input name="source" placeholder="source" />
<input name="category" placeholder="category"/>
<input type="submit" name="submit" />
</form>
演示:
http://jsfiddle.net/someprimetime/bnPwN/5/
您似乎在寻找对象表示,而不是数组。
jQuery不支持开箱即用的serializeObject()
。然而,这个插件似乎正是你想要的。
未测试,但:
function serializeObject(serializedArray){
var serializedObj={};
serializedArray.forEach(function(i){
serializedObj[i.name]=i.value;
});
return serializedObj;
}