如何在Django中将JSON传递给Ajax请求?

时间:2017-08-24 11:53:23

标签: jquery json ajax django python-3.x

我正在尝试使用以下代码将字典作为Json传递给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

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)
    }
})

一切正常,直到浏览器抛出错误AJAX error: parsererror : SyntaxError: Unexpected token < in JSON at position 0。这个错误是由于我被引导相信响应主体实际上是HTML而不是Json。

我的主要问题是:如何将结果转换为Json,以便Ajax可以顺利读取?

1 个答案:

答案 0 :(得分:1)

你需要看到几个错误。 APIView类不能包含像您实现的单个方法。你要么必须实现get或post。您可以阅读更多相关信息here

class ChartData8(APIView):
    def post(self, request):
        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 Response(data)