目前我一直在使用ajax在我的代码点火器安装中发布一些方法。我现在有一个表单,其中包含一个带有其他输入的复选框数组,并且在将值传递给post时遇到问题。目前它返回最后一个复选框的最后一个值,即使它没有被选中。
的.js
$('.flagPost').on('submit', function() {
var that = $(this), url = that.attr('action'), type = that.attr('method'), data = {};
that.find('[name]').each(function(index, value) {
var that = $(this), name = that.attr('name'), value = that.val();
data[name] = value;
});
$.ajax({
url : url,
type : type,
data : data,
success : function(response) {
$('#flagSuccess').empty().append(response).fadeIn('slow').delay(3000).fadeOut(800);
}
});
return false;
});
html的
<div class="form-group">
<label for="email" class="col-sm-4 control-label">Email</label>
<div class="col-sm-8">
<input type="email" class="form-control input-sm" name="email" id="email" placeholder="Email Address" value="<?php echo set_value('email');?>">
</div>
<span class="help-block"></span>
</div>
<div class="form-group">
<label class="control-label col-sm-4">Issues/Problems</label>
<div class="col-sm-8">
<label class="checkbox" for="problems-0">
<input type="checkbox" name="problem[]" id="problems-0" value="Adult Content">
Adult Content
</label>
<label class="checkbox" for="problems-1">
<input type="checkbox" name="problem[]" id="problems-1" value="Spam">
Spam
</label>
<label class="checkbox" for="problems-2">
<input type="checkbox" name="problem[]" id="problems-2" value="Non-existent">
Non-existent
</label>
<label class="checkbox" for="problems-3">
<input type="checkbox" name="problem[]" id="problems-3" value="Language">
Language
</label>
<label class="checkbox" for="problems-4">
<input type="checkbox" name="problem[]" id="problems-4" value="Other">
Other
</label>
</div>
<span class="help-block"></span>
</div>
<!-- Textarea -->
答案 0 :(得分:2)
jQuery有一个serialize
method用于从表单中获取所有数据(遵循控件计数为成功的常规规则)
data = that.serialize()
答案 1 :(得分:1)
由于复选框的name属性值相同,因此它们会覆盖data
对象上的相同属性。
that.find('[name]').each(function(index, value) {
var that = $(this), name = that.attr('name'), value = that.val();
data[name] = value; //This overwrites the property
});
使用jQuery的serialize函数,而不是构建自己的对象来传递。
JS小提琴: http://jsfiddle.net/7Aysb/