[英]Send JSON object via POST from JavaScript to Python
有一個由Django支持的客戶端JavaScript和服務器端Python。 有一個數據對象: foo_data = {"foo":1, "bar":2}
。
現在,我想使用dojo/request/xhr
發送一個后請求,並發送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)
但是,它不起作用:
foo_data
,則python無法將其正確識別為JSON對象,並且無法使用json.loads
讀取它。 JSON.parse
編碼foo_data
因為它已經是一個對象! request.POST
是一個空的QueryDict
request.body
具有字符串單詞object
(而不是真實對象) 任何想法如何解決這個問題?
目標:從JS-> Python發送JSON對象並在服務器端讀取它。
dojo.xhr已過時,請考慮在此處使用dojo/request
更多信息:
https://dojotoolkit.org/reference-guide/1.10/dojo/request/xhr.html#dojo-request-xhr
有關發布到服務器的實時示例,您可以查看此頁面的源代碼: 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
});
}
);
關於問題中的代碼示例,您尚未發布服務器端代碼。 但是您可以嘗試使用JSON.stringify()
將數據傳遞到服務器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.