[英]Passing a list form the front-end (react) to the back-end (django)
I am using React for my front-end and I have a list that I want to process in my back-end (I am using DJango for my back-end) What are the possible ways for me to pass my array list from the front-end to the back-end.我在前端使用 React,我有一个要在后端处理的列表(我在后端使用 DJango)从前端传递数组列表的可能方法是什么-端到后端。
I tried saving to create objects of my list and save them in the DB and then process them but it did not work!我尝试保存以创建列表的对象并将它们保存在数据库中,然后处理它们,但没有用! (or maybe I did not know how to use it correctly).
(或者也许我不知道如何正确使用它)。
mylist= ['a','b','c'];
// somewhere here or laterI want to pass mylist to the back end.
fetch('http://localhost:8000/getSentences').then((response) => response.json()).then(function(data) {
console.log(data);
}
I do not expect any result because I did not pass the data that I need to work on!我不期望任何结果,因为我没有传递我需要处理的数据!
If you are using the native fetch API for sending data to server you can send it via this way:如果您使用本机 fetch API 将数据发送到服务器,您可以通过以下方式发送它:
fetch('http://localhost:8000/getSentences', {
method: 'POST', //or your desired method here
body: JSON.stringify(listHere)
})
Fetch have an options
object when we create an API call, you can send data in it and on the server you will get the data in request object with body parameter.当我们创建 API 调用时,Fetch 有一个
options
对象,您可以在其中发送数据,并且在服务器上您将通过 body 参数获取请求对象中的数据。
Mean while in server you can do:在服务器中,您可以执行以下操作:
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
# body is now your list which you have passed from front end.
NOTE: If you are thinking to pass data in the URL, I'll prefer not to do this because its a complete list, we usually use URL params when we want to get something and we just need to send one or two variables to the server.注意:如果你想在 URL 中传递数据,我不想这样做,因为它是一个完整的列表,当我们想要获取某些东西时,我们通常使用 URL 参数,我们只需要将一两个变量发送到服务器。 The way which I have described is the best and its a standard.
我所描述的方式是最好的,也是一种标准。
You can't pass the array directly,你不能直接传递数组,
Use jQuery.param(yourObject)
.使用
jQuery.param(yourObject)
。
The param() method creates a serialized representation of an array or an object that can be understandable by various frameworks like php, ruby, django etc. param() 方法创建一个数组或对象的序列化表示,可以被各种框架(如 php、ruby、django 等)理解。
For again converting it to python再次将其转换为 python
from urllib import parse
value = parse.parse_qs(self.request.POST.get('name'))
Note that using prase you can lost some information, so recheck your data after getting it in python.请注意,使用prase可能会丢失一些信息,因此在python中获取数据后重新检查数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.