【发布时间】:2016-05-12 07:41:50
【问题描述】:
我使用 ajax 传递 json 数组以在 django 中查看。但我无法获得每个 json 对象的值。当我调试并显示 AttributeError 对象时没有属性“标签”和“值”。请帮我解决这个问题。这是我的代码 ajax 和视图中的代码:
var jsonArr = [];
$('#btnSave').on('click', function () {
$('.form-group').each(function () {
debugger;
value = $(this).find("input[name='ValueRight']").val()
label = $(this).find("input[name='LabelRight']").val()
jsonArr.push({
label: label,
value: value
})
var jsonText = JSON.stringify(jsonArr);
$.ajax({
url: '{% url 'add_label_value' %}',
method: 'POST',
dataType: 'JSON',
data: {
'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(),
'jsonText': jsonText
},
success: function (data) {
alert(data);
}
});
})
console.log(jsonArr)
})
view.py
def add_label_value(request):
if request.method == 'POST':
try:
if request.is_ajax():
order_header = OrderHeader()
jsonText = json.loads(request.POST.get('jsonText'))
for x in jsonText:
order_header.label = x.label
order_header.value = x.value
order_header.save()
except OSError as e:
error = messages.add_message(request, messages.ERROR, e, extra_tags='add_label_value')
html = '<p>This is not ajax</p>'
return HttpResponse(html)
【问题讨论】:
-
你能展示你的django视图方法吗?我猜这个问题是视图在 AJAX 发送的数据中期望字段
label和value,但您只是发送字段csrfmiddlewaretoken和jsonText。 -
在您的视图中添加一些打印或日志记录。
request.POST、request.POST.get('jsonText')和jsonText的值是多少? -
你为什么要抓
OSError?我看不出有什么会引发这种情况的。 -
如果我想收到 json 数组,我必须使用命令 request.POST.get('jsonText')