2017-08-24 71 views
1

我想傳遞一個字典作爲一個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可以順利讀取結果?

+0

你肯定不發送json所以它不會被解析。從您的意見發送json –

+0

如何從我的意見發送json?你能舉一個小例子嗎? –

+0

看到我的回答如下 –

回答

1

情侶你需要看的錯誤。 APIView類不能像你實現的那樣包含單獨的方法。您必須實現獲取或發佈。你可以閱讀更多關於它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) 
0

更換

return render(request,template_name, {Response(data)}) 

if request.is_ajax(): 
    return Response(data) 
else: 
    return render(request,template_name, data) 
+0

但是渲染過程呢?怎樣才能同時發送渲染和數據? –

+0

編輯,嘗試新版本 –

相關問題