Home > Software design >  Sending a list value via ajax to view in Django
Sending a list value via ajax to view in Django

Time:01-06

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

CodePudding user response:

You load it back from json:

import json

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