【问题标题】:How to get response data from long polling?如何从长轮询中获取响应数据?
【发布时间】:2019-09-17 12:58:39
【问题描述】:

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

ajax

$('.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】:

    您的代码没有意义。您应该从您的 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)
    

    【讨论】:

    • 非常感谢。我认为这一切都可以在一个视图中完成。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 2019-05-28
    • 2016-01-08
    相关资源
    最近更新 更多