【发布时间】:2021-10-02 20:11:30
【问题描述】:
我有一个这样的页面
{% for product in products %}
<div class="col-lg-4">
<img alt="" class="thumbnail" src="{{ product.images.all.0.image.url }}">
<div class="box-element product">
<h5><strong>{{ product.name }}</strong></h5>
<hr>
<button data-product="{{ product.id }}" data-action="add"
class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button>
<a data-product="{{ product.id }}" data-action="Save" class="btn btn-outline-secondary detail"
href="{% url 'detail' %}"> Detail</a>
.....
当用户点击详细信息时,它应该根据他点击的详细信息按钮转到另一个页面以显示产品的详细信息,所以我制作了这样的 detail.js 文件
var detailBtns = document.getElementsByClassName("detail") //get all add to cart button with class update-cart
for (i = 0; i < detailBtns.length; i++) {
detailBtns[i].addEventListener('click', function(){
var productId = this.dataset.product
var action = this.dataset.action
console.log('productId:', productId )
console.log(current_user)
GetDetail(productId, action) // this function will be called and will pass product id and action in body to your view for further processing.
})
}
function GetDetail(productId, action){
console.log("func")
var url = '/detail/'
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) =>{
console.log('data:',data)
location.reload()
})
}
在 views 中有一个函数连接到 URL detail/
def detail(request):
data = json.loads(request.body)
productId = data['productId']
action = data['action']
product = Product.objects.get(id=productId)
context = {
'product':product
}
print(productId)
return render(request, 'detail.html', context)
但是当我点击任何产品的详细信息时出现错误“JSONDecodeError。预期值:第1行第1列(字符0)”
【问题讨论】:
-
你能分享一下
request.body有什么吗?
标签: javascript html json django render