2015-02-08 41 views
0

我想通過ajax將基於類的視圖中的字符串傳輸到客戶端。如何在基於類的視圖中使用ajax返回字符串

這是我的觀點,這從另一種觀點認爲

class TeamCreateView_Ajax(TeamCreateView): 
    def render_to_response(self, context, **response_kwargs): 
     return HttpResponse("asdf") 

出於某種原因,繼承,此傳輸將一直呈現由TeamCreateView而不是字符串「ASDF」整個網頁。

class TeamCreateView_Ajax(TeamCreateView): 
    def dispatch(self, request, *args, **kwargs): 
     return HttpResponse("asdf") 

另一方面,這正確地傳送「asdf」。

什麼給?

回答

0

通常,使用ajax,我們使用json/xml進行通信以將信息從服務器發送到網頁。例如:

class SomeView(TemplateView): #I used template view because it has get method 

    def render_to_response(self, context, **response_kwargs): 
        data = {} 
        data['some_data'] = 'asdf' 
        return HttpResponse(json.dumps(data), content_type="application/json") 

而且在腳本:

$.ajax({ url: url, 
      type: "get", 
      success: function (data) { 
      alert(data.some_data); 
      }) 
+0

因爲我重要的邏輯嵌入我的方法選擇render_to_response壓倒一切的get(我不能覆蓋get()方法)將繞過render_to_response()這個 – Ben 2015-02-14 01:31:19

+0

檢查我的更新答案。 @Ben – ruddra 2015-02-14 14:14:44

相關問題