如何在python中通过AJAX发布值的数组?

时间:2013-09-05 13:40:39

标签: python ajax django jquery

我将复选框的值存储在数组中并通过AJAX发送。在console.log(searchIDs)中,我获得了所选复选框的正确o / p,但 views.py 中的print searchIDs仅打印最后一个索引值,即如果我选择One和Two,它只会打印两个。我哪里错了?

这是我的代码:

<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

1 个答案:

答案 0 :(得分:3)

django提供帮助函数getlist来帮助您获取param的id列表

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