Adam Starrh
Adam Starrh

Reputation: 6968

Phantom Brackets in Ajax Call when sending an Array to Django

I am trying to send a normal javascript array through an Ajax call and something weird is happening.

Here's my function:

// Save new Strategy
$('.tab-pane').on('click', 'button.saveStrat', function() {

      var stratType = $('#typeValue').val();   // Set by newEntry method in swot-nav.js
      var label = $('#newStratLabel').val();           // Form element in new_swot_modal.html
      var details = $('#newStratDetails').val();       // Form element edit_swot_modal.html
      var entries = [];

      // Build a list of SWOT entries that the user has identified as associated to this strategy.
      $('input.entryCheckbox[type=checkbox]').each(function () {
           if (this.checked) {
               entries.push($(this).val());
           }
         });

      console.log(entries);

      $.ajax({
          url: '/add_swot_strategy/',
          type: "POST",
          data: {
              'type': stratType,
              'label': label,
              'details': details,
              'entries': entries
          },

          dataType: 'json',
          success: function (data) {
              appendNewItem(data, swotType)
          }
      });

      resetAddForm()

  });

And here is how my Django test server receives it:

<QueryDict: {'label': [''], 'type': ['A'], 'details': [''], 'entries[]': ['16', '23', '26']}>

What's with the extra brackets after the entries label? Is this intended behavior?

Can I go ahead and do it this way or am I breaking the rules?

Upvotes: 1

Views: 436

Answers (1)

Adam Starrh
Adam Starrh

Reputation: 6968

This is expected behavior.

https://github.com/django/django/blob/master/django/utils/datastructures.py

Obtain the list data with: request.POST.getlist('entries')

Upvotes: 2

Related Questions