Javascript Django项目中的JSONDecodeError
我是初学者。我在django电子商务网站课程中所做的一切都是通过链接完成的,但它对我不起作用。我还尝试了其他堆栈溢出解决方案,但都没有帮助。当我转到/update_item/且数据未显示在终端中时,出现此错误: 期望值:第1行第1列(字符0) cart.jsJavascript Django项目中的JSONDecodeError,javascript,json,django,Javascript,Json,Django,我是初学者。我在django电子商务网站课程中所做的一切都是通过链接完成的,但它对我不起作用。我还尝试了其他堆栈溢出解决方案,但都没有帮助。当我转到/update_item/且数据未显示在终端中时,出现此错误: 期望值:第1行第1列(字符0) cart.js var updateBtns = document.getElementsByClassName('update-cart') for (i = 0; i < updateBtns.length; i++) { updateBt
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()
});
}
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 %}
{products%中产品的%s}
{{product.name}}
添加到购物车
{{产品价格|浮动格式:2}}印尼国家电力公司
{%endfor%}
视图.py的第2行中的请求.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)
究竟是什么调用函数updateUserOrder
?我没有看到任何调用它的东西?你是对的,我忘了在循环中调用函数,现在它工作了,谢谢你仍然没有工作,并且显示相同的错误你试过data=request.POST吗?MultiValueDictKeyError现在打印数据,看看你是否从前端获取值我没有在for循环中调用函数。。。我错了,但是谢谢你的帮助
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)