django支持跨域ajax响应

时间:2014-01-28 11:47:10

标签: ajax json cross-domain cors django-generic-views

我有以下代码,我正在尝试使用用于JSONResponseMixinAjaxResponseMixinLoginRequiredMixin的django大括号执行跨域ajax请求。

在视图中我有

class SomeListView(LoginRequiredMixin, JSONResponseMixin, AjaxResponseMixin, ListView):
    model = SomeModel
    template_name = 'some_list.html'
    paginate_by = 16
    content_type = "text/html"

    def get_queryset(self):
        print 'get_queryset called'
        return SomeModel.objects.filter(user=self.request.user)

    def get_context_data(self, **kwargs):
        print 'get_context_data called'
        context = super(SomeListView, self).get_context_data(**kwargs)
        #some more data
        return context

    def get_ajax(self, request, *args, **kwargs):
        print 'get_ajax called'
        qset = self.get_queryset()
        json_dict = list(qset.values('name', 'id'))
        return self.render_json_response(json_dict)

@login_required
def randomTest(request):
    req ={"id":3,"src":'https://d2csjd0bj2nauk.cloudfront.net/products/bd63b797-9640-4e80-9bb4-0ca41201fbd2_s.jpg',"rstate":True}
    req2={"id":4,"src":'https://d2csjd0bj2nauk.cloudfront.net/products/bd63b797-9640-4e80-9bb4-0ca41201fbd2_s.jpg',"rstate":False}
    lreq = [req,req2]
    json_dict = lreq
    response = json.dumps(json_dict)
    response = HttpResponse(response, mimetype="application/json")
    return response

我已经在django-cors的帮助下实施了角色,当我打电话给randomTest时,我得到了成功的反应。我们有网址

url(r'^cbooth/$', SomeListView.as_view(), name='cbooth'),
url(r'^fbooth/', randomTest),

当我从允许的跨域或相同的域尝试它并且给出obj响应时,这个ajax正在工作

ajaxOpts =  {
           url:'http://localhost:8000/fbooth/',
           dataType:'json',
           xhrFields: {withCredentials: true},
           complete: function(data){
                console.log("complete");
                els=data.responseText;
                els=JSON.parse(els);
                console.log(els);                        
           }
        };
        $.ajax(ajaxOpts);

这个ajax正在为跨域提供html响应但是对同一域的obj响应。

ajaxOpts =  {
           url:'http://localhost:8000/cbooth/',
           dataType:'json',
           xhrFields: {withCredentials: true},
           complete: function(data){
                console.log("complete");
                els=data.responseText;
                els=JSON.parse(els);
                console.log(els);                        
           }
        };
        $.ajax(ajaxOpts);

问题是django braces的问题或者我做错了什么?

0 个答案:

没有答案