request.is_ajax()==单击“返回"按钮时为true? [英] request.is_ajax() == True when clicking back button?

查看:62
本文介绍了request.is_ajax()==单击“返回"按钮时为true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django应用,该应用根据页面请求是否为Ajax返回不同的响应.

I have a Django app that returns different responses based on whether the page request is Ajax or not.

当我查看页面时,导航至其他地方,然后单击后退"按钮,该请求将呈现为 request.is_ajax()的值为True.因此,JSON输出显示在浏览器中,而不是生成的HTML.

When I view a page, navigate elsewhere, then click the back button, the request gets rendered as if the value for request.is_ajax() is True. So the JSON output is showing up in the browser rather than the generated HTML.

为什么会发生这种情况,我该如何预防呢?

Why might this be happening and how can I prevent it?

这是在Chrome(16.0.912.77)中发生的情况

This is happening in Chrome (16.0.912.77)

令人困惑的是,我实际上是在后台 am 对该URL发出ajax请求.基本上,我重载了URL,以便它既可以以格式化的HTML显示内容,又可以以JSON形式提供(以便随着时间的推移发生更改,我可以实时更新THML页面).最令人沮丧的是,最简单的解决方案是为Ajax版本创建一个单独的Django url模式.

Confusing matters is that I actually am making ajax requests of that URL in the background. Basically, I overloaded an URL so that it both displays the content in formatted HTML but also makes it available as JSON (so as changes happen overtime I can update the THML page in real time). It may be that the easiest solution, frustrating as it is, is to create a separate Django url pattern for the Ajax version.

推荐答案

如果请求是通过 XMLHttpRequest 发出的,则返回True.检查 HTTP_X_REQUESTED_WITH 标头中的字符串"XMLHttpRequest".

Returns True if the request was made via an XMLHttpRequest, by checking the HTTP_X_REQUESTED_WITH header for the string 'XMLHttpRequest'.

所以问题实际上是为什么按下后退按钮会将标头附加到请求?在任何浏览器中,这似乎都不是适当的行为.那么,您尝试过使用哪种浏览器?它们是否都具有相同的行为?如果没有,您在问题浏览器中安装了哪些插件可能会导致此类问题?

So the question is really why does pressing the back button attach that header to the request? That doesn't seem like appropriate behavior in any browser. So, which browser(s) have you tried this on? Do they all have the same behavior? If not, which addons do you have installed in the offending browser that might cause such an issue?

编辑

您不一定必须创建一个完全独立的视图和/或urlpattern,但是使用查询字符串可能不是一个坏主意.在REST中,同一个视图返回多种不同格式的情况并不少见,但这通常是这样的:

You don't necessarily have to create an entirely separate view and/or urlpattern, but it might not be a bad idea to use a query string. In REST it's not uncommon for the same view to return multiple different formats, but this is usually done like:

http://domain.com/some/view/      # Returns HTML
http://domain.com/some/view/?json # Returns JSON

这是一个小小的折衷,可能足以解决您的问题.

It's a small compromise that might be enough to get around your issue.

这篇关于request.is_ajax()==单击“返回"按钮时为true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆