I'm attempting to use Ajax to send a JavaScript array to Django. Here's my code:
document.getElementById('input-generate').onclick = () => {
// Get the token
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
// Create new request add token
const generateRequest = new XMLHttpRequest();
generateRequest.open('POST', '/generate');
generateRequest.setRequestHeader('X-CSRFToken', csrftoken);
generateRequest.onload = () => {
console.log('generateRequest');
};
// Add the motif to send with the request
const data = new FormData();
console.log(notes);
// [{…}] 0: {duration: "4", note: "E4", dot: false} length: 1 __proto__: Array(0)
data.append('motif', notes);
// Send request
generateRequest.send(data);
};
In views.py:
@require_http_methods(["POST"])
def generate(request):
# See if method was post
if request.method == "POST":
# Retrive seed
seed = request.POST.get("motif")
print(seed)
print(type(seed))
# Sanity check
if not seed:
return JsonResponse({"succes": False}, status=400)
# Return the seed
return JsonResponse({"seed": seed}, status=200)
However, when I print out seed and its type, all I get is:
[object Object]
<class 'str'>
How can I display the actual array being sent?
By the way, the array I'm sending contains strings encoding notes, for example:
notes = [{duration: "4", note: "E4", dot: false}, {duration: "8", note: "D4", dot: false}, {duration: "2", note: "F4", dot: false}]