[md]
我们在传统的表单里提交ajax时,需要手动打包:
var params = sendForm.serializeArray();
var postData = {};
params.map(function (obj) {
postData[obj.name] = obj.value;
});
但当你的input的name的值出现title[a]这样的格式时 就会错误的提交name为title[a]了。
解决代码:
function packetArrayToObj(postData, keyName, val) {
var keyAll,key1;
var reg_=/[([^]]+)]/ig;
keyAbc = keyName.match(reg_);//[a], [b], [c]
key1 = keyName.split('[')[0]; //content[a][b][c]
keyAll = [key1].concat(keyAbc);
function diguiData($data, keys) {
key_ = keys.shift();
key_ = key_.replace(/([|])/g, '');
if(typeof $data[key_] =='undefined') {
if(keys.length) {
$data[key_] = diguiData({}, keys);
} else {
$data[key_] = val;
}
return $data;
} else {
if(keys.length) {
$data[key_] = diguiData($data[key_], keys);
} else {
$data[key_] = [$data[key_]].concat([val]);
}
return $data;
}
}
return diguiData(postData, keyAll);
}
var params = sendForm.serializeArray();
var postData = {};
params.map(function (obj) {
if(obj.name.indexOf('[') !=-1) {
postData = packetArrayToObj(postData, obj.name, obj.value);
} else {
postData[obj.name] = obj.value;
}
});
postData = {"row": postData};