Mohammad Moradi
Mohammad Moradi

Reputation: 35

Sending a list value via ajax to view in Django

I'm trying to send a list from template to view Django via ajax. After I send that, I get same list as a string format!

index.html

<script>
   ...
   var provinces_list = []
   var obj = document.getElementById('objectSelected');
   for (var i=0; i<obj.length; i++) {
        provinces_list.push(obj.options[i].value)
   }
   var jsonText = JSON.stringify(provinces_list);

   $.ajax({
      method: "GET",
      data: {
         'P_list': jsonText
      },
      url: '{% url '...' %}',
      dataType: 'json',
      success: function (context) {
        ...
      }
   })
</script>

view.py

provincesList = request.GET.get('P_list')

when I debug, I get the list as str format:

provincesList={str}'["X","Y","Z"]'

I want to get value as a list. how can do that? thanks in advance

Upvotes: 1

Views: 304

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

You load it back from json:

import json

provincesList = json.loads(request.GET['P_list'])

Upvotes: 1

Related Questions