Ajax POST和Django Tastypie

时间:2011-08-22 16:19:44

标签: jquery ajax 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

3 个答案:

答案 0 :(得分: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"
});

答案 1 :(得分:3)

我在中间件中添加了XS_SHARING_ALLOWED_HEADERS,解决了这个问题。

https://gist.github.com/1164697

答案 2 :(得分: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请求来执行实际创建。