我尝试检查多个复选框,而不是全部使用Ajax调用。它工作得很好,但当我取消选中它们时,只有一个未选中,其他的都会再次选中。
Ajax调用检查和取消选中:
$(function(){
$('input[type=checkbox]').bind("change",function(){
if($(":checkbox[path='description']:checked").length > 0 ){
$.ajax({
type: 'POST',
url: 'check.html',
data: { "id": $(this).attr('cid')},
success: function(data){
}
});
}
else{
$.ajax({
type: 'POST',
url: 'uncheck.html',
data: { "id": $(this).attr('cid')},
success: function(data){
}
});
}
});
});
html部分,用于检查点的循环:
<c:forEach var = "c" items = "${planid.checkpoints}" varStatus="status">
<c:if test = "${c.st eq s.name and c.rw eq r.name}">
<p><input cid="${c.id}" class= "case" path="description" type="checkbox" value="${c.description}" />
<c:out value = "${c.description}"></c:out>
<security:authorize access="hasRole('admin')">
<a href="/gefp/jsp/Edit.html?id=${c.id}">[Edit]</a>
</security:authorize>
</p>
</c:if>
</c:forEach>
在控制器中:
@RequestMapping("/jsp/check.html")
@ResponseBody
public ResponseEntity<String> check(@RequestParam Long id, HttpSession session){
String u=SecurityUtils.getUsername();
User user=userDao.getUser(u).get(0);
user.getId();
Checkpoint cp = userDao.getCheckpoint(id);
user.getCheckpoints().add(cp);
userDao.saveUser(user);
return new ResponseEntity<String>( HttpStatus.OK );
}
@RequestMapping("/jsp/uncheck.html")
@ResponseStatus(HttpStatus.OK)
public void uncheck(@RequestParam Long id){
String u=SecurityUtils.getUsername();
User user=userDao.getUser(u).get(0);
user.getId();
Checkpoint cp = userDao.getCheckpoint(id);
user.getCheckpoints().remove(cp);
userDao.saveUser(user);
}
我通过解决了这个问题
$(function(){
$('input[type=checkbox]').change(function(){
var checked = $(this).is(':checked');
if(checked){
$.ajax({
type: 'POST',
url: 'check.html',
data: { "id": $(this).attr('cid')},
success: function(data){
}
});
}
else{
$.ajax({
type: 'POST',
url: 'uncheck.html',
data: { "id": $(this).attr('cid')},
success: function(data){
}
});
}
});
});