如何从长轮询中获取响应数据?

问题描述 投票:0回答:1

我在long polling(1.11)做了Django。但我不明白为什么JsonResponse会返回未定义的值?

阿贾克斯

$('.txt_link > a').on('click', function() {
  $.ajax({
    type: 'GET',
    url: '',
    success: function(data){
      console.log(data.title)              //undefined
    }
  })
})

视图

class ProviderCreateView(CreateView):
    form_class = ProviderForm
    template_name = 'provider_create.html'

    def form_valid(self, form):
        ...

    def get_context_data(self, **kwargs):
        ctx = super(ProviderCreateView, self).get_context_data(**kwargs)
        ctx['organizations'] = Organization.objects.filter(user=self.request.user)
        last_organization = Organization.objects.filter(user=self.request.user).first()

        if self.request.is_ajax():
            while True:
                curr_organization = Organization.objects.filter(user=self.request.user).first()
                if last_organization != curr_organization:
                    template_ajax = render_to_string(
                        template_name='provider_create.html',
                        context=ctx
                    )
                    return JsonResponse({
                        'success': True,
                        'template': template_ajax,
                        'pk': curr_organization.pk,
                        'title': curr_organization.title
                        })

                time.sleep(2)
        return ctx
jquery json ajax django long-polling
1个回答
3
投票

你的代码没有意义。您应该从CreateView创建一个单独的视图,然后在那里路由您的GET请求。

例:

class OrganizationView(View):
    def get(self, request, *args, **kwargs):
         curr_organization = Organization.objects.filter(user=request.user).first()

         if last_organization != curr_organization:  # What is `last_organization`? Calculate it above and this condition will work.
             data = {
                 'success': True,
                 'curr_organization_pk': curr_organization.pk,
                 'curr_organization_title': curr_organization.title
             }
         else:
             data = {'success': False}
         return JsonResponse(data)
© www.soinside.com 2019 - 2024. All rights reserved.