2 ajax同时调用会导致视图出现问题

时间:2017-11-12 20:48:50

标签: javascript jquery python ajax django

我正在使用django-el-pagination使用ajax呈现2个查询集(with open("file.sql","w") as f: f.write(output) Post)。因此,当我单击Commentmore posts时,它会在相应的查询集中加载下一批对象。这是JS函数显示:

more comments

以下是根据点击的内容从函数($('body').on('click', '.endless_more', function() { console.log($(this).html()); var user_queryset; if ($(this).html() === 'more posts') { console.log('POSTS'); user_queryset = 'user_posts' } else if ($(this).html() === 'more user comments') { user_queryset = 'user_comments'; console.log('COMMENTS'); } else { console.log('none'); } $.ajax({ type: 'GET', url: window.location.href, data: { 'user_queryset': user_queryset } }) }); user_posts接收数据的视图。

user_comments

现在,JS工作正常 - 它根据点击的内容发送正确的数据。因此,在ajax调用期间,视图中的def profile(request, user, extra_context=None): ... page_template = 'profile/profile.html' print('LOAD') if request.is_ajax(): print('Requests:', request.GET) user_queryset = request.GET.get('user_queryset') print('Queryset:', user_queryset) if user_queryset == 'user_posts': page_template = 'profile/user_posts.html' elif user_queryset == 'user_comments': page_template = 'profile/user_comments.html' elif user_queryset == 'user_inbox': page_template = 'profile/user_inbox.html' else: pass else: pass print('Template:', page_template) context = {'user_posts': user_posts, 'user_comments': user_comments, 'page_template': page_template} return render(request, page_template, context) 已成功更新,但它会呈现父模板(page_template)而不是所选的子模板(profile.htmluser_posts.html) 。原因可能是因为同时发送了2个ajax调用 - 一个来自user_comments.html,另一个来自我的JS函数。我知道因为我的印刷声明有2个电话。首先,当我第一次加载整个页面时,这是我的打印语句:

django-el-pagination

这是正确的 - 它加载父模板。

现在点击LOAD Template: profile/profile.html

时,这是我的打印陈述
more posts

你可以看到它经历了我的观点两次。为什么这样做?第一次获取分页数据,然后下次获取单击按钮(在此实例中为LOAD Requests: <QueryDict: {'querystring_key': ['page'], 'page': ['2']}> Queryset: None Template: profile/profile.html LOAD Requests: <QueryDict: {'user_queryset': ['user_posts']}> Queryset: user_posts Template: profile/user_posts.html )。即使它被调用两次,第二次有正确的模板加载(user_posts),所以它仍然可以工作 - 但它没有,它仍然加载父模板。有谁知道为什么会发生这种情况以及如何解决这个问题?我认为实际代码没有任何错误;如果我在user_posts.html中将其更改为user_queryset = 'user_posts',那么它可以正常工作 - 仅加载request.is_ajax()。但是它似乎无法处理有两个查询集。

0 个答案:

没有答案