我在Django中使用Ajax的第一步,我遇到了复选框的问题。当我点击复选框时,一切都正常工作:我得到了值,复选框设置为True。如果我再次单击该复选框,我会得到值,但它不会返回False。这是代码:
HTML
<table>
<tr>
<td>
Some text
<form action="mytemplate.html" method="GET" id="myform">{% csrf_token %}
<input id="chktest" name="test" type="checkbox" value= "{{number}}">
</form>
</td>
</tr>
<tr>
<td>
Some text
<form action="mytemplate.html" method="GET" id="myform">{% csrf_token %}
<input id="chktest" name="test" type="checkbox" value= "{{number}}">
</form>
</td>
</tr>
</table>
**JQUERY**
<script type="text/javascript">
$(document).ready(function() {
$('table tr td #chktest').click(function() {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(response) {
// on success..
},
error: function(e, x, r) {
// on error...
}
});
return false;
});
});
</script>
**MYVIEW.PY**
...
if request.is_ajax():
number = request.GET['number']
# I save the number in my db
message = "Hello!"
return HttpResponse(json.dumps({'message': message}))