2013-04-05 93 views
0

我一直在閱讀關於過去一小時的XMLHttpRequest,但我似乎可以做到這一點.. 所以,我有一個django服務器與tastypie和另一個服務器/端口上的JavaScript客戶端,和當我嘗試做一個jQuery後,我收到了Django tastypie XMLHttpRequest無法加載

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的呼叫從本地主機發布: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"); 
     }); 

    } 
}); 

UPDATE:

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 

我到底做錯了什麼?

+0

什麼是您實際發出請求的網址。它似乎像你的瀏覽器認爲它的交叉請求 – dusual 2013-04-05 16:45:26

+0

它的本地主機:80張貼到本地主機:8000 – psychok7 2013-04-05 16:46:06

回答

1

嗨,我認爲你基本上是一個交叉原點請求。

要發起一個跨源請求,瀏覽器會發送帶有HTTP頭的請求。此標頭的值是爲頁面提供服務的網站。

要允許請求,它會在其響應中發送一個Access-Control-Allow-Origin標頭。標題的值指示允許哪些源網站。

Access-Control-Allow-Origin: localhost:80 

從本質上講,你需要讓你的服務器端的選項請求發回的 訪問控制允許來源頭部

請通過這個美好的想法

Cross domain POST query using Cross-Origin Resource Sharing getting no data back

+0

但我使用django tastypie默認資源設置,以便tastypie在帖子上自動創建一個新的資源..我應該改變它看起來更像這個答案http://stackoverflow.com/a/5260062/977622?有沒有更簡單的方法? – psychok7 2013-04-05 18:40:23

+0

你可以嘗試添加一箇中間件進行處理或者什麼的.https://gist.github.com/strogonoff/1369619 Tastypie支持的選項參見:https://github.com/toastdriven/django-tastypie/pull/70 – dusual 2013-04-05 20:09:00

+0

我幾乎在那裏我想,現在我只在django上得到內部服務器錯誤,這是我的json:http://paste.ubuntu.com/5688899/任何想法爲什麼? – psychok7 2013-04-08 09:44:16