我正在尝试将数据从 tempermonkey 中的脚本(通过表单读取用户输入)传输到 django。 传输有效,但我无法在 python 中使用数据(我认为我在格式上做错了)。
这是我在 tempermonkey 中的脚本示例:
GM_xmlhttpRequest({
method: "POST",
url: "www.example.com",
data: datasend,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
onload: function(response) {
alert(response.responseText);
}
});
datasend 包含一个像这样的对象数组:
[{"name" : "Pippo" , "surname" : "Pluto" , "address" : "street xxx" , "number" : "1234"},{"name" : "aaa" , "surname" : "bbb" , "address" : "street xxx" , "number" : "4321"},{"name" : "y" , "surname" : "x" , "address" : "street xxx" , "number" : "333"}]
这是我的观点.py
def index(request):
data=request.POST
dataTransform=(json.loads(json.dumps(request.POST)))
return HttpResponse(dataTransform)
响应是:
(u'[{"name" : "Pippo" , "surname" : "Pluto" , "address" : "street xxx" , "number" : "1234"},{"name" : "aaa" , "surname" : "bbb" , "address" : "street xxx" , "number" : "4321"},{"name" : "y" , "surname" : "x" , "address" : "street xxx" , "number" : "333"}]',u")
长度=1的字典。我如何访问每个元素? 我的目标是将这些信息保存在数据库中。
感谢您的帮助!
最佳答案
首先以 JSON 形式发送数据:
GM_xmlhttpRequest({
method: "POST",
url: "www.example.com",
data: JSON.stringify(datasend),
headers: {
"Content-Type": "application/json"
},
onload: function(response) {
alert(response.responseText);
}
});
并正确接收:
def index(request):
dataTransform=json.loads(request.body.decode("utf-8")))
for item in dataTransform:
print(item["name"])
return HttpResponse(dataTransform)
关于javascript - 将 Post 数据从 python 发送到 django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36523995/