我在通过 ajax post 调用访问嵌套对象时遇到了一些问题。这是我的 js:
$.ajax({
url: "/api/locate/",
type: "POST",
data: {start:
{
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
},
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
console.log(start);
},
success: function(data) {
console.log(data);
}
})
在我看来,检索数据的唯一方法是执行以下操作:
latitude = request.POST['start[latitude]']
longitude = request.POST['start[longitude]']
考虑到我最理想的开始是包含纬度和经度键的字典,这有点糟糕。我确实意识到这种格式是由于内容类型被设置为“application/x-www-form-urlencoded”,但是当我将其更改为“application/json”时,数据必须从 request.body 中解码:
decoded = request.body.decode('utf8')
data = json.loads(decoded)
这又会引发以下 ValueError:
期望值:第 1 行第 1 列(字符 0)
解码后的字符串是:
start%5B0%5D%5Blatitude%5D=31.736784000000004&start%5B0%5D%5Blongitude%5D=-106.473027
你们中有人成功地正确加载了嵌套对象,还是我坚持使用第一种方法?
编辑:使用 Django 1.6.2 和 python 3.4
请您参考如下方法:
当您发送 json 数据时,请在您的对象上使用 JSON stringifier。
data: JSON.stringify({start:
{
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
})
如果你传递一个普通对象作为数据,it is converted to a query string ,无论您将什么声明为 Content-Type。
