我正在尝试向Django发送AJAX发布请求。我有一个有效的JSON对象,可以在浏览器中打印/查看/字符串化它,但是当它到达Django时,其键值未评估(请参见第二代码块中的Django视图)。
JS:
/* prettify payload for back */
var makeUpdatePayload = function(fieldType, fieldArray) {
var orderInfo = fieldArray.map(function(field, idx) {
var fieldInfo = field.split('-field-')
return {
'pk': fieldInfo[1],
'order': idx
}
});
return {[fieldType]: orderInfo}
};
/* post payload */
var updateFieldOrder = function( payload ) {
console.log('in ajax')
console.log(JSON.stringify(payload)) // {"search":[{"pk":"9","order":0},{"pk":"7","order":1},{"pk":"6","order":2},{"pk":"8","order":3},{"pk":"5","order":4},{"pk":"4","order":5}]}
$.ajax({
type: "POST",
url: "update_field_order/",
dataType: "json",
data: JSON.parse( JSON.stringify(payload)),
});
};
var payload = makeUpdatePayload('search', ["search-field-9", "search-field-7", "search-field-6", "search-field-8", "search-field-5", "search-field-4"])
updateFieldOrder(payload);
在我的Django视图中:
def update_field_order(request, recipe_pk):
print('post')
print(request.POST) # <QueryDict: {'search[0][pk]': ['9'], 'search[0][order]': ['0'], 'search[1][pk]': ['7'], 'search[1][order]': ['1'], 'search[2][pk]': ['6'], 'search[2][order]': ['2'], 'search[3][pk]': ['8'], 'search[3][order]': ['3'], 'search[4][pk]': ['5'], 'search[4][order]': ['4'], 'search[5][pk]': ['4'], 'search[5][order]': ['5']}>
我已经尝试过JSON.stringify,然后尝试JSON.parse-在发送之前对有效负载进行设置,但这没有帮助,我仍然看到相同的格式。使用JSON.stringify(payload)
,我得到了预期的输出:
`<QueryDict: {'{"search":[{"pk":"9","order":0},{"pk":"7","order":1},{"pk":"6","order":2},{"pk":"8","order":3},{"pk":"5","order":4},{"pk":"4","order":5}]}': ['']}>`
为什么会这样?
我可以看到发送时未正确评估数据:
答案 0 :(得分:2)
我不完全确定键没有被评估的意思,但是要在POST请求中发送对象,您应该在ajax调用中将其字符串化:
data: JSON.stringify(payload),
,然后在您的视图中,从request.body
检索JSON并使用json
模块加载它:
import json
...
payload = json.loads(request.body.decode("utf-8"))