【问题标题】:JSONDecodeError in Django projectDjango项目中的JSONDecodeError
【发布时间】:2021-08-19 00:12:38
【问题描述】:

我是初学者。我在链接中的 django 电子商务网站课程中做所有事情,但它对我不起作用。我还尝试了其他堆栈溢出解决方案,但它们没有帮助。当我转到 /update_item/ 并且数据未显示在终端中时出现此错误:

预期值:第 1 行第 1 列(字符 0)

tutorial

cart.js

var updateBtns = document.getElementsByClassName('update-cart')

for (i = 0; i < updateBtns.length; i++) {
updateBtns[i].addEventListener('click', function(){
    var productId = this.dataset.product
    var action = this.dataset.action
    console.log('productId:', productId, 'Action:', action)
    console.log('USER:', user)
})
}
function updateUserOrder(productId, action){
console.log('User is authenticated, sending data...')

    var url = '/update_item/'

    fetch(url, {
        method:'POST',
        headers:{
            'Content-Type':'application/json',
            'X-CSRFToken':csrftoken,
        },
        body:JSON.stringify({'productId':productId, 'action':action})
    })
    .then((response) => {
       return response.json();
    })
    .then((data) => {
        location.reload()
    });
}

views.py

def updateItem(request):
data = json.loads(request.body)
productId = data['productId']
action = data['action']
print('Action:', action)
print('Product:', productId)

return JsonResponse('Item was added', safe=False)

store.html

<div class="row">
{% for product in products %}
    <div class="col-lg-4">
        <img class="thumbnail" src="{{ product.imageURL }}">
        <div class="box-element product">
            <h6><strong>{{product.name}}</strong></h6>
            <hr>

            <button data-product="{{product.id}}" data-action="add"  class="btn btn-outline-secondary add-btn update-btn update-cart">Add to Cart</button>
            <a class="btn btn-outline-success" href="#">View</a>
            <h4 style="display: inline-block; float: right"><strong>{{product.price|floatformat:2}}PLN</strong></h4>

        </div>
    </div>
{% endfor %}

【问题讨论】:

  • 函数updateUserOrder到底是什么?我没有看到任何调用它的东西?
  • 你说得对,我忘了循环调用函数,现在可以了,谢谢

标签: javascript json django


【解决方案1】:

views.py 的 line2 中的 request.body 包含字节而不是字符串。因此,您需要将其解码为字符串才能获取数据。 所以views.py 中的代码必须看起来像-:

def updateItem(request):
    data = request.POST
    productId = data['productId']
    action = data['action']
    print('Action:', action)
    print('Product:', productId)

return JsonResponse('Item was added', safe=False)

【讨论】:

  • 仍然无法工作并显示相同的错误
  • MultiValueDictKeyError 现在
  • 打印数据并查看是否从前端获取值
  • 我没有在 for 循环中调用函数...我的错误,但感谢您的帮助
猜你喜欢
  • 2018-05-13
  • 1970-01-01
  • 2017-04-16
  • 2021-05-06
  • 2014-02-10
  • 2020-12-10
  • 1970-01-01
  • 1970-01-01
  • 2020-03-27
相关资源
最近更新 更多