跨浏览器问题:首次加载后,firefox不会从php文件加载图像

ber*_*436 2 javascript ajax firefox jquery cross-browser

我有动态生成新的验证码图像的PHP代码.我有一个HTML按钮,通过一个jquery事件处理程序刷新一个新的验证码图像.单击按钮(并触发jquery事件处理程序)会在chrome和safari中生成一个新图像 - 但不会在firefox中生成.firefox有什么不同?如何让它在Firefox中运行?

javascript控制台在任何浏览器中都没有显示错误.

这是代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'/>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script>
           $(document).ready(function () {
                     $("#submitButton").click(function(event) {                     
                        $("#captchaText").attr('src', 'cryptographp.inc.php?intro=false'); //this line does not generate a fresh image in firefox
                    });
           });

    </script>
    <link rel="stylesheet" type="text/css" href="stylesheet2.css">

</head>


<body>
<div class="wrapper">
    <div id='header'>
     </div>

      <div id='captchaPanel'>

        <div id='top'>
            <div id='fillerTop'>

            </div>
            <div id='captcha'>
                <img id='captchaText' src='cryptographp.inc.php?intro=false'> </img>
            </div>
        </div>
    </div>


    <div id='submitDiv'>
    <input id='submitButton' type="submit" class="button" value="Submit"/>
    </div>

</div>

</body>
Run Code Online (Sandbox Code Playgroud)

也许我需要通过显式的AJAX调用来做到这一点?像这样的东西(我在猜测语法).

$.ajax({
    url: 'cryptographp.inc.php?intro=false',
    success: function(data) {  $("#captchaText").attr('src', data); }
});
Run Code Online (Sandbox Code Playgroud)

Ita*_*tay 9

备选方案#1 - 使用额外的 query string

确保图像未从缓存加载的一种非常简单的方法是添加一个额外query string的参数(不需要在其上读取server side),因此无法URL使用两次(在同一台计算机上) .

在这种情况下,我使用了milliseconds since epochby by Date().getTime().

var now = new Date().getTime();
$("#captchaText").attr('src', 'cryptographp.inc.php?intro=false&time=' + now);
Run Code Online (Sandbox Code Playgroud)

这将导致请求URL如下:

cryptographp.inc.php?intro=false&time=1379998715616
cryptographp.inc.php?intro=false&time=1379998715618
cryptographp.inc.php?intro=false&time=1379998715636
etc...
Run Code Online (Sandbox Code Playgroud)

备选方案#2 - 使用PHP禁用HTTP缓存

您还可以cryptographp.inc.php使用以下代码禁用您的缓存(即使您选择备选方案#1,这可能是一个好主意):

header("Content-Type: application/json");
header("Expires: on, 01 Jan 1970 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
Run Code Online (Sandbox Code Playgroud)

就像Nathaniel Granor在评论中所说,在某些浏览器src attribute中将图像更改为相同URL可能不会产生新的图像HTTP request,因此建议您先将其切换到不同的位置.

例如(JS):

  $("#captchaText").attr('src', 'temp.png')
                   .attr('src', 'cryptographp.inc.php?intro=false');
Run Code Online (Sandbox Code Playgroud)
  • PS - 在这种情况下,我建议temp.png将包含一个非常小的图像(如透明图像)的真实文件1px * 1px.