[英]Can't get value of each json object in view django
我使用ajax傳遞json數組以在Django中查看。 但是我無法獲取每個json對象的值。 當我調試和移動AttributeError對象時,沒有屬性'label'和'value'。 請幫我解決這個問題。 這是我的代碼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)
Python不是Javascript,而字典(即json.loads
返回的內容)與對象之間是有區別的。 您不能使用點號引用字典鍵,而必須使用字符串鍵。
order_header.label = x['label']
order_header.value = x['value']
views.py
import json
def add_label_value(request):
getjson = json.loads(request.body)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.