jquery – Ajax POST和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

解决方法

您在通话中明确声明了您的内容类型,但您并未具体说明您的 jQuery.ajax()通话.

更新您的JavaScript以准确定义内容类型:

$.ajax({
  type: 'POST',contentType: "application/json"
});

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...