我想傳遞一個字典作爲一個JSON與下面的代碼一個Ajax請求:如何將JSON傳遞給Django中的Ajax請求?
Views.py
from rest_framework.response import Response
class ChartData8(APIView):
def tickets_per_day_results(request):
if request.method == "POST":
template_name = 'personal_website/tickets_per_day_results.html'
year = request.POST.get('select_year', None)
week = request.POST.get('select_week', None)
....do stuff...
data = {"label_number_days": label_number_days,
"days_of_data": count_of_days}
return render(request,template_name,{Response(data)})
Response
是我使用的數據轉換成JSON格式的類但後來我不得不把它作爲字典{}
包裝,所以我可以避免錯誤context must be a dict rather than Response
。直到瀏覽器拋出我的錯誤AJAX error: parsererror : SyntaxError: Unexpected token < in JSON at position 0
template_1
$.ajax({
method: "POST",
url: endpoint,
dataType: 'json',
contentType: "application/json",
headers: {"X-CSRFToken": $.cookie("csrftoken")},
success: function(data){
console.log(data)
label_number_days = data.label_number_days
days_of_data = data.days_of_data
setChart()
},
error: function(jqXHR,error_data, errorThrown){
console.log("error on data")
console.log(error_data)
console.log(JSON.stringify(jqXHR))
console.log("AJAX error: " + error_data + ' : ' + errorThrown)
}
})
一切正常確定。這個錯誤是由於我引導我相信響應體實際上是HTML而不是Json。
我的主要問題是:如何將結果轉換爲Json,以便Ajax可以順利讀取結果?
你肯定不發送json所以它不會被解析。從您的意見發送json –
如何從我的意見發送json?你能舉一個小例子嗎? –
看到我的回答如下 –