我有一个带有简单表单的简单页面:
<div data-role="page" id="main">
<div data-role="header">
<h1>Page Title</h1>
</div>
<div data-role="content">
<form id="add_form">
<input type="text" name="name" placeholder="Name" />
<textarea name="description" placeholder="Description"></textarea>
<button data-role="button" id="cancel-form" >Cancel</button>
<input type="submit" value="Add" />
</form>
</div>
<div data-role="footer">
<h4>Page Footer</h4>
</div>
</div>
然后
$(document).on( "pageshow", "#main", function() {
new MAIN();
});
var MAIN = (function () {
function MAIN() {
$("#add_form").submit(function(){
console.log($(this).serialize());
return false;
});
}
return MAIN;
})();
问题是我得到name=&name=test&description=&description=some content
,
序列化字符串中基本上重复..
关于jQuery页面上写着:
Warning: selecting both the form and its children will cause duplicates in the serialized string.
但我不会那样做,不是吗?
关于这个问题有什么想法吗?
编辑:
我找到了一个可行的解决方案
var MAIN = (function () {
function MAIN() {
var _this = this;
$("#add_form").submit(function(){
console.log(_this.serializeObject($(this).serializeArray()));
return false;
});
}
MAIN.prototype.serializeObject = function(a) {
var o = {};
$.each(a, function() {
if (o[this.name]) {
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;
};
return MAIN;
})();
这将在 console.log Object {name: "werwerwer", description: "erewwewerwerw"}
最佳答案
var MAIN = (function () {
function MAIN() {
var _this = this;
$("#add_form").submit(function(){
console.log(_this.serializeObject($(this).serializeArray()));
return false;
});
}
MAIN.prototype.serializeObject = function(a) {
var o = {};
$.each(a, function() {
if (o[this.name]) {
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;
};
return MAIN;
})();
关于jquery - 如何在提交表单时使用 jQuery 和 jQuery Mobile 在序列化字符串中给出重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14887111/