我正在使用cordova构建地图应用,并发出发布请求以发送以下JSON(功能)
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-6.6865857,
53.2906136
]
},
"properties": {
"amenity": "pub",
"name": "The Parade Ring"
}
}
这是发送请求的JQuery代码
function savePub(feature){
$.ajax({
type: "POST",
headers: {"csrfmiddlewaretoken": csrftoken},
url: HOST + URLS["savePub"],
data: {
pub_feature: JSON.stringify(feature)
},
contentType:"application/json; charset=utf-8"
}).done(function (data, status, xhr) {
console.log(data + " " + status);
pubDialogAlert("Pub saved",feature);
}).fail(function (xhr, status, error) {
showOkAlert(error);
console.log(status + " " + error);
console.log(xhr);
}).always(function () {
$.mobile.navigate("#map-page");
});
}
在Django后端收到请求时,我不确定为什么当我打印请求正文时看起来像这样,
b'pub_feature=%22%7B%5C%22type%5C%22%3A%5C%22Feature%5C%22%2C%5C%22geometry%5C%22%3A%7B%5C%22type%5C%22%3A%5C%22Point%5C%22%2C%5C%22coordinates%5C%22%3A%5B-6.6865857%2C53.2906136%5D%7D%2C%5C%22properties%5C%22%3A%7B%5C%22amenity%5C%22%3A%5C%22pub%5C%22%2C%5C%22name%5C%22%3A%5C%22The+Parade+Ring%5C%22%7D%7D%22'
,当我尝试对其进行解码然后使用json.loads()时,会引发此错误
@api_view(['POST'])
def save_pub(request):
if request.method == "POST":
data = request.body.decode('utf-8')
received_json_data = json.loads(data)
return Response(str(received_json_data) + " written to db", status=status.HTTP_200_OK)
JSONDecodeError at /savepub/
Expecting value: line 1 column 1 (char 0)
我假设是因为一旦解码了二进制字符串,由于这些字符%22等而无法将其转换为有效的JSON,但是我不知道解决方案是什么。
任何帮助将不胜感激。 谢谢
答案 0 :(得分:1)
您在这里混淆了两件事,即表单编码和JSON格式。您所拥有的是带有一个键pub_feature
的表单编码帖子,其值是JSON对象。
相反,您应该直接发布JSON:
data: JSON.stringify(feature),
然后您应该能够像已经完成的那样加载它-尽管请注意,确实应该让DRF为您处理