我试图将我的序列化表格数据发送到django,它应该作为列表“[video,audio]”存储在“mylist”中。 views.py每次都返回0,无论我在表单上检查什么方框。
html表单
<form id="myform" method="POST">
<input type="checkbox" name="list" value="audio"/> Audio<br />
<input type="checkbox" name="list" value="video"/> Video<br />
<input type="submit" value="Get Custom Library!" />
</form>
jquery ajax
<script language="JavaScript">
$(document).ready(function() {
$("#myform").submit(function() {
$.ajax({
type: "POST",
url: 'django/builder/buildit',
data: $(this).serialize(),
success: function(response){
alert(response);
}
});
return false;
});
});
</script>
views.py
from django.http import HttpResponse
def main(request):
mylist = request.POST.getlist('list')
message = 0
for item in mylist:
if item == 'video':
message = 'vid'
elif item == 'audio':
message = 'aud'
return HttpResponse(message)
答案 0 :(得分:1)
您没有给data
参数赋予键值对,但您甚至不必走那么远 - 您不必自己收集复选框值。你可以替换它:
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: 'django/builder/buildit',
data: myCheckboxes,
success: function(response){
alert(response);
}
});
这样,使用serialize:
$.ajax({
type: "POST",
url: 'django/builder/buildit',
data: $('#myform').serialize(),
success: function(response){
alert(response);
}
});