2011-08-22 85 views
8
curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"latlong": "test"}' http://localhost:8000/geo/api/geolocation/ 

上述工作正常,但是當我嘗試複製下面的ajax中的POST時,我得到500錯誤。Ajax POST和Django Tastypie

$.ajax({ 
    type: 'POST', 
    url: 'http://localhost:8000/geo/api/geolocation/', 
    data: '{"latlong": "test"}', 
    success: latlongSaved(), 
    dataType: "application/json", 
    processData: false, 
}); 

錯誤消息:

{"error_message": "The format indicated 'application/x-www-form-urlencoded' had no available deserialization method. Please check your ``formats`` and ``content_types`` on your Serializer." .... } 

值得注意的,這是跨域和我使用的是通過GIT中發現django-crossdomainxhr-middleware.py:要點

如果我添加內容類型Ajax調用是這樣的:

contentType: "application/json" 

我得到這個錯誤回:

XMLHttpRequest cannot load http://localhost:8000/geo/api/geolocation/. Request header field Content-Type is not allowed by Access-Control-Allow-Headers. 
Request URL:http://localhost:8000/geo/api/geolocation/ 
Request Method:OPTIONS 
Status Code:200 OK 
Request Headersview source 
Access-Control-Request-Headers:Origin, Content-Type, Accept 
Access-Control-Request-Method:POST 
Origin:http://localhost:3000 
Response Headersview source 
Access-Control-Allow-Methods:POST,GET,OPTIONS,PUT,DELETE 
Access-Control-Allow-Origin:* 
Content-Type:text/html; charset=utf-8 
Date:Tue, 23 Aug 2011 07:59:49 GMT 
Server:WSGIServer/0.1 Python/2.6.1 
+0

檢查文檔 - 您可能需要在url字符串中設置json選項。 – Marcin

+0

你可以發佈'curl'請求標題和jQuery標題之間的差異嗎?您可以在Firebug內的控制檯標籤中看到jQuery標題。 –

回答

7

你被明確聲明內容類型在您的來電curl,但你沒有被具體您jQuery.ajax()電話。

更新你的JavaScript來定義到底是什麼類型的內容將是:

$.ajax({ 
    type: 'POST', 
    url: 'http://localhost:8000/geo/api/geolocation/', 
    data: '{"latlong": "test"}', 
    success: latlongSaved(), 
    dataType: "application/json", 
    processData: false, 
    contentType: "application/json" 
}); 
+0

爲了清楚起見,你可以提一下'dataType'的作用嗎? –

+0

已經嘗試過了,上面添加了錯誤消息。 –

+0

你正在做跨域AJAX調用。這對JSON不起作用,你必須使用JSONP – Eduardo

3

添加XsSharing(https://gist.github.com/1164697)到settings.py中:

MIDDLEWARE_CLASSES = [ 
    ..., 
    'django-crossdomainxhr-middleware.XsSharing' 
] 

然後使用下面的JavaScript,使Ajax調用:

$.ajax({ 
    type: 'POST', 
    url: 'http://localhost:8000/geo/api/geolocation/', 
    data: '{"latlong": "test"}', 
    success: latlongSaved(), 
    contentType:'application/json', 
    dataType: 'application/json', 
    processData: false, 
}); 

請注意,data必須是格式正確的JSON字符串,否則jQuery將默默地忽略ajax調用並且什麼也不做。

背後的情況是,ajax電話會先發出OPTIONS /geo/api/geolocation/。由於響應頭由XsSharing中間件修改,因此jQuery將發出另一個POST /geo/api/geolocation請求來執行實際創建。

+0

This:「請注意,數據必須是格式正確的JSON字符串,否則jQuery將默默地忽略ajax調用並且什麼都不做」,幫了我很多!謝謝 –