如何从长轮询中获取响应数据?
Posted
技术标签:
【中文标题】如何从长轮询中获取响应数据?【英文标题】: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
【问题讨论】:
【参考方案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)
【讨论】:
非常感谢。我认为这一切都可以在一个视图中完成。以上是关于如何从长轮询中获取响应数据?的主要内容,如果未能解决你的问题,请参考以下文章