简体   繁体   中英

How to get the array of values posted via AJAX in python?

I'm storing the values of checked boxes in an array and sending it via AJAX. In console.log(searchIDs) I get the correct o/p of selected checked boxes, but print searchIDs in views.py only prints the last index value, ie if I select One and Two, it will only print Two. Where I'm going wrong?

Here is my code:

<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[]')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM