0

Im trying to send my serialized form data to django where it will should be stored in "mylist" as a list "[video, audio]". views.py return 0 everytime no matter what boxes I check on my form.

html form

<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)
4

1 に答える 1

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);
        }
    });
于 2012-06-13T20:27:48.023 に答える