当我运行json加载时,我将ajax调用发布到了/ cart / total,我在其中使用post来转储存储在本地存储中的JSON字符串,它显示了错误。
TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not QueryDict
我的JSON字符串在解析之前看起来像是一个空的字段,这在Django中是我不知道的
<QueryDict: {'{"32":1,"33":1,"34":2}': ['']}>
<script>
function addtocart(mitem, mprice) {
if(localStorage.getItem('cart')==null){
// var mobj = {}
// var countQ ={}
var price = String(mprice)
var mobj = { [String(mitem)]: 1 }
var countQ = {'Quantity':1}
var storeobj = JSON.stringify(mobj)
var storeCountq = JSON.stringify(countQ)
localStorage.setItem('cart', storeobj)
localStorage.setItem('quantity',storeCountq)
console.log(localStorage.getItem('cart'))
}else{
var data = localStorage.getItem('cart')
var quant = localStorage.getItem('quantity')
var obj = JSON.parse(data)
var parsequant = JSON.parse(quant)
if(obj.hasOwnProperty(String(mitem))){
obj['%s',mitem]++
parsequant['Quantity']++
var storeobj = JSON.stringify(obj)
console.log(localStorage.getItem('cart'))
var storeCountq = JSON.stringify(parsequant)
localStorage.setItem('cart', storeobj)
localStorage.setItem('quantity', storeCountq)
}
else{
obj[String(mitem)] = 1
parsequant['Quantity']++
var storeobj = JSON.stringify(obj)
console.log(localStorage.getItem('cart'))
var storeCountq = JSON.stringify(parsequant)
localStorage.setItem('cart', storeobj)
localStorage.setItem('quantity', storeCountq)
}
}
}
function ajaxcall(){
$.ajax(
{
type: "POST",
url: "/cart/total",
data: localStorage.getItem('cart'),
success: function () {
console.log("sent tdata")
}
})
}
ajaxcall()
</script>
<p style="position: absolute; bottom: 0px"><button class="button" style="width: 200px" onclick="addtocart( '{{M.Menu_Item_Id}}', '{{M.Menu_ItemPrice}}' )" >Add to cart</button>
查看功能
@csrf_exempt
def cartpricecalculator(request):
if request.method == 'POST':
data = json.loads(request.POST)
print(request.POST)
return HttpResponse('200 Okay')
我不确定自己做错了什么,感谢您的帮助。
答案 0 :(得分:0)
尝试:
在JS中,传递字典而不是字符串。根据ajax的文档,数据必须是具有键和值的对象,或者是具有键和值的对象的字符串。
参考:https://api.jquery.com/jQuery.ajax/
function ajaxcall(){
$.ajax(
{
type: "POST",
url: "/cart/total",
data: {'cart': localStorage.getItem('cart')},
success: function () {
console.log("sent tdata")
}
})
}
在python中
@csrf_exempt
def cartpricecalculator(request):
if request.method == 'POST':
cart_data = json.loads(request.POST.get('cart', '{}'))
print(request.POST)
print(request.POST.get('cart'))
return HttpResponse('200 Okay')
答案 1 :(得分:0)
request.POST
用于表单数据。您需要;
data = json.loads(request.body)