我在long polling
(1.11)中做了Django
。但是我不明白为什么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
答案 0 :(得分: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)