您好我有以下示例表单
<form id="search" method="GET" action="/results">
<input type="text" name="name">
<input type="checkbox" name="rating" value="1">
<input type="checkbox" name="rating" value="2">
<input type="checkbox" name="rating" value="3">
<input type="checkbox" name="rating" value="4">
<input type="checkbox" name="rating" value="5">
<input type="submit" value="Submit" name="submit">
</form>
当我在选择一些评级复选框后提交表单并使用JQuery serialize(),如下所示
$('#search').submit(function() {
var $form = $(this);
var strFormData = $form.serialize();
//var objFormData = $form.serializeArray();
//var strFormDataParamResult = $.param(objFormData);
});
我得到了像这样的strFormData的例子
"name=help&rating=1&rating=2&rating=3"
有没有办法将任何具有相同名称的参数组合到此结果中
"name=help&rating=1,2,3"
通过操纵serializeArray()的结果然后使用$ .param(..)?
如果有的话,有没有这方面的例子呢?
感谢您的帮助。
答案 0 :(得分:1)
如果您使用约翰内斯的帖子建议,那么您应该将复选框中的名称属性更改为“rating []”。
否则如果你真的需要用GET来做,你可以试试这个:
$('#search').submit(function() {
var serialized = $(this).serialize(),
ratings = '';
$('#search input[type=checkbox]:checked').map(function(i, n) {
ratings += (i ? ',' : '') + n.value;
});
serialized += '&rating='+ratings;
...
});
答案 1 :(得分:1)
这是我最终的解决方案.. serializeArray和操作对象似乎有点复杂,下面不是更好但是它做了我想要的。
// Combine key=value pairs in escaped serialised form data that have the same key
// example: "&rating=5&rating=4&rating=3" becomes "&rating=5,4,3"
function combineSerialisedFormData(strEscapedSerialisedFormData) {
var arrFormData = strEscapedSerialisedFormData.split("&");
var dictCombinedKeys = {};
for (var i = 0; i < arrFormData.length; i++) {
var arrParam = arrFormData[i].split("=");
var strKey = arrParam[0];
var strValue = arrParam[1];
if (strKey !== "" && strValue !== "") {
if (typeof (dictCombinedKeys[strKey]) === "undefined") {
dictCombinedKeys[strKey] = strValue;
}
else {
dictCombinedKeys[strKey] += "," + strValue;
}
}
}
// { name : "help" , rating : "5,4,3,2,1,0", test : "" }
// change this object into an array of key value pairs like this
// ["name=help","rating=5,4,3,2,1,0","test="]
var arrKeyValuePairs = [];
for (var key in dictCombinedKeys) {
if (dictCombinedKeys.hasOwnProperty(key)) {
arrKeyValuePairs.push(key + "=" + dictCombinedKeys[key]);
}
}
return arrKeyValuePairs.join("&");
}