javascript - 将 Post 数据从 python 发送到 django

标签 javascript json django python-3.x xmlhttprequest

我正在尝试将数据从 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/

相关文章:

c# - 如何使用 C# 将 JSON 发布到服务器?

android - 数据未进入回收站 View 项目

django - 用于 Django 身份验证的用户管理应用程序

python - Django: AttributeError: 'bool' 对象没有属性 'expire'

javascript - 使用 javascript 取消表单提交不起作用

javascript - HTML5 input=时间不会通过javascript设置

javascript - 更改连续旋转中的 CSS 动画持续时间

c# - 通过 Javascript 禁用转发器内的特定验证器

Django 拒绝保存表单上显示的日期

java - 应为 BEGIN_OBJECT,但为 STRING - 没有键的 json