Skip to main content
 首页 » 编程设计

python之jquery.get 不在 Firefox 上执行 xhr 请求

2025年05月04日25unruledboy

我刚刚进入 jquery 的世界,对 javascript 也很陌生。我有一个像下面这样的小 javascript 片段:-

<script type="text/javascript"> 
 $(function(){ 
    $('a').click(function(event){ 
        event.preventDefault(); 
        $.get('/_add_navigation_',function(response){ 
        $('#themaincontents').html(response); 
        }) 
   }) 
</script> 

html 看起来像这样:-

<a href="?toaddnavigation">CLICK Me</a> 
<div id="themaincontents"></div> 

在服务器端,我通过类似的方式进行 xhr header 检查

 if request.is_xhr: send response else:redirect somewhere 

虽然这段代码在 Chrome 和 Opera 上运行良好,但在 Firefox 上它表现得有点奇怪。服务器不发回响应,而是进行重定向。这意味着它说没有 xhr header 。为什么在其他两个浏览器上运行正常时会发生这种情况?
(我使用的是 Firefox 3.6.12)
更新 - 我刚刚查看了 Firefox 的请求 header ,我发现没有 X-Requested-With:XMLHttpRequest header ,但它存在于 Chrome 中。

请您参考如下方法:

并非所有浏览器都发送相同的 header ,您不能依赖它们在浏览器之间保持一致。最简单的方法就是不依赖浏览器发送东西,而是自己手动发送东西:

$.get('url', { 
    xhr: 'yes' // add this extra parameter here 
}, function(){ 
 
}); 

然后检查服务器上的 GET 变量,而不是浏览器可能发送也可能不发送的 header 。