【问题标题】:How to pass a JSON to a an Ajax request in Django?如何将 JSON 传递给 Django 中的 Ajax 请求?
【发布时间】:2018-02-02 07:05:15
【问题描述】:

我正在尝试使用以下代码将字典作为 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 可以顺利读取?

【问题讨论】:

  • 你肯定不会发送 json 所以它不会被解析。从您的视图中发送一个 json
  • 如何从我的视图中发送 json?能举个小例子吗?
  • 在下面查看我的答案

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


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 2015-11-22
    • 2012-02-12
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    相关资源
    最近更新 更多