简体   繁体   English

将数组 object 从 Ajax 传递到 Django 框架

[英]Pass array object from Ajax to Django Framework

Ajax code Ajax代码

Assume arry1D has values [0,1,2,3,4]假设arry1D的值为[0,1,2,3,4]

$.ajax({
  url: "{% url 'form_post' %}",
  type: "POST",
  data: {
    arry1D: arry1D,
    'csrfmiddlewaretoken': tk
  },
  cache:false,

});

Below the code of getModelAttribute() function in view.py在 view.py 中getModelAttribute() view.py的代码下方

I'm trying to access arry1D[0] element but I could not.我正在尝试访问arry1D[0]元素,但我不能。

def getModelAttribute(request, self=None):
    print("In Method")
    if request.method == "POST" and request.is_ajax():
        arry1D = request.POST.get('arry1D')
        print(arry1D[0])
        return JsonResponse({'arry1D':arry1D})

to get access to your arry1D array object you need getlist() and not get()要访问您的arry1D数组 object 您需要getlist()而不是get()

change this line更改此行

arry1D = request.POST.get('arry1D')

to

arry1D = request.POST.getlist('arry1D')

refer to this topic https://docs.djangoproject.com/en/3.0/ref/request-response/#django.http.QueryDict.getlist参考这个话题https://docs.djangoproject.com/en/3.0/ref/request-response/#django.http.QueryDict.getlist

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM