2014-11-04 52 views
3

我知道它的一個非常基本的問題,但是在浪費了我整整一天之後,我問了這個問題。我只是用發送以下AngularJS代碼數據的Django:

$http.post('/data/creation', 
        { 
       html: 'a' 

      }). 
       success(function(data, status, headers, config) { 
       // this callback will be called asynchronously 
       // when the response is available 
        console.log(data); 
        console.log(status); 
        console.log(headers); 
        console.log(config); 
       }). 
       error(function(data, status, headers, config) { 
       // called asynchronously if an error occurs 
       // or server returns response with an error status. 
        console.log(status); 
        console.log(data); 
       }); 

,並在Django:

@csrf_exempt 
def snippets_post(request): 
    html = False 
    css = False 
    js = False 
    JSONdata = False 
    response = "You're looking at the results of question %s." 
    if request.method == 'POST': 
     try: 
      JSONdata = request.POST.get('data', False) # it was [] in actual 
     except: 
      JSONdata = 'ERROR' 

    return HttpResponse(JSONdata) 

我作爲響應,「讓虛假通過更換數據POST.get結果HTML是相同「。我不知道這裏出了什麼問題。任何人都可以在這裏幫助我嗎?

感謝

+0

請您返回一個靜態值,並檢查..返回的HttpResponse(「後值」)..我很懷疑有關網址是否觸及此片段或某處? – Asik 2014-11-04 19:16:39

+0

溝通是完美的,我越來越虛假,因爲POST.get無法獲得'數據'或'HTML'。問題是如何得到這個? – 2014-11-04 19:21:36

+0

請點擊F12,使用螢火蟲或鉻網絡標籤追蹤請求,並查看url是否包含html/data請求處理..如果它存在,那麼問題在於你的服務器端代碼... – Asik 2014-11-04 19:35:07

回答

4

其實,當我們使用$ HTTP的POST AngularJs發送數據時,將其與內容類型=「應用/ JSON」服務器發送數據。 Django不理解這種格式。所以你無法獲得發送的數據。

解決方案是使用下面的配置來改變內容類型標題:

app.config(['$httpProvider', function ($httpProvider) { 
     $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 
}]); 
+0

有趣!很高興知道這件事。感謝通知:) – Asik 2014-11-05 18:23:44

+0

謝謝,這也適用於Turbogears框架 – 2015-02-18 11:52:27