我试图将tempermonkey中的脚本数据(按表单读取userinput)传输到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"}]
这是我的view.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的字典。我如何访问每个元素? 我的目标是将这些信息保存在数据库中。
感谢您的帮助!
答案 0 :(得分:0)
首先将您的数据作为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)