我将复选框的值存储在数组中,并通过AJAX发送。在console.log(searchIDs)中,我得到了选定复选框的正确o / p,但是views.py中的print searchIDs仅显示了最后一个索引值,即,如果我选择“一”和“二”,则只会打印“二”。我要去哪里错了?

这是我的代码:

<script>
  $(function() {

    $( "#dialog-form" ).dialog({
      autoOpen: false,
      height: 300,
      width: 350,
      modal: true,
      buttons: {
        "Add": function() {

            var searchIDs = [];
            $("#dialog-form input:checkbox:checked").map(function(){
                searchIDs.push($(this).val());
            });

            $.ajax({
            type: "POST",
            url: "/dashboard/",
            data : { 'searchIDs' : searchIDs },
            success: function(result){
                console.log(searchIDs);
                $("#widgets").html(result);
                }
            });

            $( this ).dialog( "close" );

        },

    Cancel: function() {
          $( this ).dialog( "close" );
        }
      },

    });

    $( "#add_widget" ).click(function() {
        $( "#dialog-form" ).dialog( "open" );
      });
  });
  </script>

<body>

<div id="dialog-form" title="Create new user">
    <input type="checkbox" value="One">One</input><br>
    <input type="checkbox" value="Two">Two</input><br>
    <input type="checkbox" value="Three">Three</input><br>
    <input type="checkbox" value="Four">Four</input><br>
</div>

<div id="widgets" class="ui-widget"></div>
<button id="add_widget">Add Widget</button>


</body>


View.py

if request.is_ajax():
        searchIDs = request.POST['searchIDs[]']
        print searchIDs

最佳答案

django提供了一个辅助函数getlist来帮助您获取参数的ID列表

request.POST.getlist('searchIDs[]')

10-06 07:44