Jquery Django tastypie XMLHttpRequest无法加载
在过去的一个小时里,我一直在阅读关于XMLHttpRequest的文章,但我似乎可以让这项工作正常进行。。 因此,我在另一个服务器/端口上有一个带有tastypi的django服务器和一个JavaScript客户端,当我尝试执行jquerypost时,我得到了一个Jquery Django tastypie XMLHttpRequest无法加载,jquery,django,post,xmlhttprequest,tastypie,Jquery,Django,Post,Xmlhttprequest,Tastypie,在过去的一个小时里,我一直在阅读关于XMLHttpRequest的文章,但我似乎可以让这项工作正常进行。。 因此,我在另一个服务器/端口上有一个带有tastypi的django服务器和一个JavaScript客户端,当我尝试执行jquerypost时,我得到了一个 XMLHttpRequest cannot load http://127.0.0.1:8000/api/smart/rating/. Origin http://localhost is not allowed by Access-
XMLHttpRequest cannot load http://127.0.0.1:8000/api/smart/rating/. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
我在客户端收到Xmlthhprequest错误消息
Django代码:
class RatingResource(ModelResource):
city = fields.ForeignKey(CityResource, 'city')
user = fields.ForeignKey(UserResource, 'user')
class Meta:
queryset = Rating.objects.all()
resource_name = 'rating'
#authentication = BasicAuthentication()
#authorization = DjangoAuthorization()
我的jquery呼叫从localhost:80发送到localhost:8000:
$('#star').raty({
path: "../assets/img/",
score : rating,
click : function(score, evt) {
window.rate_app = score;
var url = "http://127.0.0.1:8000/api/smart/rating/";
//var comment = $('#textarea').val();
var comment = "teste do php";
console.log(cityId);
$.post(url,{city : '/api/smart/city/'+cityId+'/' ,comment : comment,id:'4',resource_uri:'/api/smart/rating/4/',rating : score, user: '/api/smart/auth/user/2/'},function(data,status){
if (data=="error")
console.log("error");
else
console.log("success");
});
}
});
更新:
HTTP/1.0 401未经授权
curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"city": "/api/smart/city/35/", "comment": "teste do php", "id": "4", "resource_uri": "/api/smart/rating/4/", "rating": "3","user_id": "/api/smart/auth/user/2/"}' `http://localhost:8000/api/smart/rating/`
HTTP/1.0 401 UNAUTHORIZED
Date: Mon, 08 Apr 2013 10:52:44 GMT
Server: WSGIServer/0.1 Python/2.7.3
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
Content-Type: text/html; charset=utf-8
Access-Control-Allow-Headers: Content-Type,*
Access-Control-Allow-Credentials: true
我做错了什么?您好,我认为您实际上是在提出跨原产地请求 要启动跨源请求,浏览器会发送带有源HTTP头的请求。此标题的值是为页面提供服务的站点 为了允许请求,它在其响应中发送一个访问控制允许源报头。标头的值指示允许哪些源站点
Access-Control-Allow-Origin: localhost:80
基本上,您需要在服务器端允许一个选项请求,该请求将
访问控制允许源标题
为了更好的主意,请仔细检查一下
您实际发出请求的url是什么。您的浏览器似乎认为这是一个跨组织的请求,它的localhost:80发布到localhost:8000,但我使用的是django-tastypie默认资源设置,因此tastypie会在发布时自动创建一个新资源。。我应该把它改成更像这个答案吗?难道没有更简单的方法吗?您可以尝试添加一个中间件来处理或其他事情。Tastypie支持选项见此:我几乎做到了,我想,现在我在django上只得到了一个内部服务器错误,这是我的json:知道为什么吗?太少的信息,你能告诉我django侧的回溯吗?我没有得到任何关于$.post的回溯,只有500个内部服务器错误,但是有$.ajax我得到了这个