![](/img/trans.png)
[英]Using jQuery ajax() to POST to a Tastypie resource results in a 404
[英]Ajax POST and Django Tastypie
curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"latlong": "test"}' http://localhost:8000/geo/api/geolocation/
以上工作正常,但當我嘗試在下面的ajax中復制POST時,我得到500錯誤。
$.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:gist找到的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
您在調用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"
});
我在中間件中添加了XS_SHARING_ALLOWED_HEADERS,解決了這個問題。
將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
請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.