2015-10-07 31 views
0

我想通過使用ajax將json數據從django視圖轉移到模板。
這裏是我ajax code將json數據從django-view發送到ajax

$(document).ready(function(){ 
    console.log("this is getting executed") 
    $.ajax({ 
      url: "/get_ecommdata/", 
      type: "get", 
      cache: "false", 
      dataType : 'json', 
      success: function(data) { 
       console.log("This is working fine") 
       alert(data) 
      }, 
      error:function(xhr, ajaxOptions, thrownError) { 
       console.log("this is error") 
       alert(xhr.status) 
      }, 
    }) 
}); 

示意圖如下:

def get_ecommdata(request): 
    print "inside get_ecommdata" 
    tempdata = ['{"square": 0, "key": 0}', '{"square": 1, "key": 1}', '{"square": 4, "key": 2}'] 
    return HttpResponse(tempdata) 

狀態代碼爲,但仍然是 「這是錯誤」 顯示在控制檯即其執行錯誤部分。

這裏是我的理解:

狀態代碼是200,即服務器正常發送數據,但有一些問題識別的數據類型。 此代碼適用於簡單文本,但不適用於json。

我的問題

能有人給我關於Django的觀點傳遞JSON數據阿賈克斯一些方向。我想我在這裏犯了一個愚蠢的錯誤。

P.S.我已經瀏覽了其他類似的帖子(json,ajax,view),但沒有一個迎合這個具體問題。

+0

使用JsonResponse:https://docs.djangoproject.com/en/1.8/ref/request-response/#jsonresponse-objects –

+0

似乎並沒有一個有效的JSON來me.You應該把它包起來在[]中,加上週圍沒有單引號,看看我的答案如果它可以幫助你。 – cafebabe1991

回答

1

導入json模塊

import json 

然後在您的請求方法試試這個

data = json.dumps([{"square": 0, "key": 0}, {"square": 1, "key": 1}, {"square": 4, "key": 2}])  

return HttpResponse(data, content_type="application/json") 

注意

使用單引號做爲程式碼中會導致如下輸出

'["{\\"square\\": 0, \\"key\\": 0}", "{\\"square\\": 1, \\"key\\": 1}", "{\\"square\\": 4, \\"key\\": 2}"]' 

它對導引頭的困惑,因此我使用了上述方法。但這取決於選擇。

+1

感謝您的解決方案。使用json.dumps確實解決了我的問題。 備案。問題在django-view中。這裏更新的代碼工作正常。 'def get_ecommdata(request): print「inside get_ecommdata」 tempdata = ['{「square」:0,「key」:0}','{「square」:1,「key」:1}', '{「square」:4,「key」:2}'] #tempdata =「hello」 tempdata1 = json.dumps(tempdata) return HttpResponse(tempdata1,content_type =「application/json」)' – Conquistador

+0

Superb: - ),但我仍然建議避免使用引號,因爲它會在結果中導致不必要的\\。你可以在你的案例中看到json.dumps的結果,它會包含令人困惑的雙斜線。但是,如果你對它好,那麼很好:-)但作爲一個答案,我認爲我們應該讓他們知道它。說啥 ? – cafebabe1991

0
def get_ecommdata(request): 
    print "inside get_ecommdata" 
    list_square = [ 
     {"square": 0, "key": 0}, 
     {"square": 1, "key": 1}, 
     {"square": 4, "key": 2} 
    ] 
    data = json.dumps(list_square) 
    return HttpResponse(data, content_type='application/json')