【问题标题】:Can't get value of each json object in view django无法在视图 django 中获取每个 json 对象的值
【发布时间】: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 发送的数据中期望字段 labelvalue,但您只是发送字段 csrfmiddlewaretokenjsonText
  • 在您的视图中添加一些打印或日志记录。 request.POSTrequest.POST.get('jsonText')jsonText 的值是多少?
  • 你为什么要抓OSError?我看不出有什么会引发这种情况的。
  • 如果我想收到 json 数组,我必须使用命令 request.POST.get('jsonText')

标签: python json ajax django


【解决方案1】:

Python 不是 Javascript,字典(json.loads 返回的内容)和对象之间存在差异。你不能用点符号来引用字典键,你必须使用字符串键。

   order_header.label = x['label']
   order_header.value = x['value']

【讨论】:

  • 如果对您有帮助,请不要忘记接受答案。
【解决方案2】:

views.py

 import json

    def add_label_value(request):
        getjson = json.loads(request.body)

【讨论】:

    猜你喜欢
    • 2019-08-11
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    相关资源
    最近更新 更多