gpt4 book ai didi

jquery - 通过ajax将数组发送到Django

转载 作者:行者123 更新时间:2023-12-01 06:13:45 26 4
gpt4 key购买 nike

我正在尝试通过 ajax 将 JavaScript 数组发送到 Django,如下所示。

main.html:

<a href=#>Click</a>

<script>
$(document).on('click', 'a', function() {

var arr = [1, 2, 3, 4];
var formData = new FormData();
formData.append('arr', arr);

$.ajax({
url: '...',
type: 'POST',
data: formData,
processData: false,
contentType: false
});

});
</script>

在服务器端:

views.py:

@csrf_exempt
def main(request):
arr = request.POST.get('arr')
print(type(arr))
print(arr)
return render(request, 'main/main.html')

结果是一个字符串:'1,2,3,4'

如果我检索数据:

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

结果是一个包含字符串的列表:['1,2,3,4']

如何获得像 [1, 2, 3, 4] 这样的真实列表?

最佳答案

Python 3+、Django 2+、jQuery

在您的模板中

data = {
key_1_string: 'Value 1 is a string',
key_2_array: ['1st Value of array', '2nd Value of array'],
key_3_int: 1234,
key_4_array_of_objects: JSON.stringify([{id: 3, name: "ABC"}, {id: 4, name: "CBA"}])
... rest of your keys/values you want to pass to Server
}

$.ajax({
url: "{% url 'ajax_url' %}",
method : "post",
dataType : "json",
data : data,
timeout: 1000,
success: function (response) {
// Do some success scripts
if (response.operation_status == 'ok') {
alert ('All done ok')
} else {
alert ('Ups. Found some error!')
}
},
error: function (response) {
// Request error. Display right error message
...
});

在你看来

from django.views.decorators.http import require_POST
from django.http import JsonResponse

@require_POST
def ajax_view_for_ajax_url:
string_value = request.POST.get('key_1_string')
array_value = request.POST.getlist('key_2_array[]')
int_value = request.POST.get('key_3_int')
array_of_objects = json.loads(request.POST.get('key_4_array_of_objects'))

# Do some magic code with all values
return JsonResponse({
'key_1':'value_1',
'operation_status': 'ok or error',
... rest of your keys/values you want to pass to Client
})

如果你不喜欢 jQuery,你可以这样发送

var xhr = new XMLHttpRequest();
xhr.open("POST", "{% url 'ajax_url' %}", true);
xhr.setRequestHeader("X-CSRFToken", formData.csrfmiddlewaretoken);
xhr.onload = function () {
// do something to response
var json = JSON.parse(this.responseText);
if (json.operation_status == "ok") {
alert ('All done ok');
} else {
alert ('Ups. Found some error!');
}
};
xhr.send(postData);

希望对你有帮助

关于jquery - 通过ajax将数组发送到Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40977166/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com