1

I would like to access option_rows data that is sent from the front end of the web application. I use an array to store a collection of objects, include text and image, and append it into formdata, send via ajax. The console log of option_rows is as the image below.

However, I couldn't access each data in the array. How could I access each element of option_rows? Please also point out what is wrong with the code below as well. Thank for answering.

Javascript code:

var option_rows = [];
option_rows.push([{option_name : option_name,
                    answer : answer,
                    option_img : option_img}]);
var formData = new FormData();
formData.append('option_rows', option_rows);
$.ajax({
  url: "{% url 'add_question' %}",
  type: 'POST',
  data: formData,
  contentType: false,
  processData: false,
  cache: false,
  success: function(){
    $("#addModal").html("");
  },
})

option_rows log: option_rows data


views.py:

def add_question(request):
    if request.method == 'POST':
        option_rows = request.POST.get('option_rows')
        print option_rows
        print type(option_rows)

output:

Python code output

  • 2
    I suggest to use JSON.stringify() formData.append('option_rows', JSON.stringify(option_rows)); Then load json in add_question - json.loads(request.body) – Davit Tovmasyan Nov 07 '18 at 06:06
  • @DavitTovmasyan using JSON.stringify() and json.loads() work for string and other data type. But for `File type`, after json.loads(), it is emptied. -In this case, the array `option_rows` includes `option_name`, `answer`, `option_img`. How to do overcome this? – Sokunthaneth Chhoy Nov 07 '18 at 07:20
  • @Sokunthaneth You're trying to send JS objects over HTTP. It won't work. You need to convert them to string. But since you're trying to send multiple objects, I guess you're stuck. Instead of sending data in an array, if you send the elements one by one, that may work. – xyres Nov 07 '18 at 08:55
  • Does this answer your question? [How do I POST an array of objects with $.ajax (jQuery or Zepto)](https://stackoverflow.com/questions/11109795/how-do-i-post-an-array-of-objects-with-ajax-jquery-or-zepto) – Brian Tompsett - 汤莱恩 Aug 23 '20 at 08:38

0 Answers0