I using ajax to passing json array to view in django. But I can't get value of each json object. When I debug and displaed AttributeError object have no attribute 'label' and 'value'. Please help me with this problem. This is my code ajax and code in view:
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 is not Javascript, and there is a difference between a dictionary - which is what json.loads
returns - and an object. You can't refer to dictionary keys with dot notation, you have to use string keys.
order_header.label = x['label']
order_header.value = x['value']
views.py
import json
def add_label_value(request):
getjson = json.loads(request.body)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.