通过 POST 将 JSON 对象从 JavaScript 发送到 Python

Send JSON object via POST from JavaScript to Python

有客户端 JavaScript 和服务器端 Python,由 Django 提供支持。有一个数据对象:foo_data = {"foo":1, "bar":2}.

现在,我想使用 dojo/request/xhr 发送 post-请求,并发送 foo_data 和另一个变量:

xhr.post(document.location.href, {
    data: {
        'is_foo': true,
        'data': foo_data
    },
    headers: { 'Content-Type': 'application/json' }
}).then(function(text){
    console.log('The server returned: ', text);
});

然后在Django的views.py文件中读取发送的数据:

def post(self, request, *args, **kwargs):
    json.loads(request.body)

但是,它不起作用:

有什么解决办法吗?

目标:从 JS 发送 JSON 对象 --> Python 并在服务器端读取它。

dojo.xhr 已弃用,请考虑在此处使用 dojo/request 更多信息:

https://dojotoolkit.org/reference-guide/1.10/dojo/request/xhr.html#dojo-request-xhr

有关 post 到服务器的实时示例,您可以查看此页面的源代码: https://dojotoolkit.org/documentation/tutorials/1.8/ajax/demo/dojo-request-xhr-post.php

这里有一些简单的用法示例:

        require(dojo/request"],
            function(request){
                    // post the data to the server
                    request.post("your/server/script", {
                        // send your data here
                        data: { yourData: 1},
                        // wait 2 seconds for a response
                        timeout: 2000

                    }).then(function(response){
                        // do smt here when operation is successfully executed
                    });

            }
        );

关于您问题中的代码示例,您还没有 post编辑服务器端代码。但是您可以尝试使用 JSON.stringify().

将数据传递到服务器