【问题标题】:Is JQuery caching image?JQuery 是否缓存图像?
【发布时间】:2012-01-14 10:28:05
【问题描述】:

我在加载图像时遇到问题。图像仅在第一次加载,之后我得到相同的图像。只有第一次去 photoHandler.ashx。 这里会发生什么? jquery 缓存图像吗?如何始终加载正确的图像? 这是我的功能:

 function getObjectFromServer()
{
var hUrl = "myHandler.ashx";
var data = {};
var data.queryStringKey = "theKey";
 $.post(hUrl, data, function(response){
    if(response.length>0)
    {
        var myObj = jQuery.parseJSON(response);
        var $photo = $("<img alt='' class='hidden' />").load(function(){
          $("#photo-container").append($photo);
          $photo.fadeIn('slow');
        }).attr('src', myObj.photoSrc);
        //myObj.photoSrc contains: photoHandler.ashx?photoId=anUniqueIdentifier
    }
 });
}

编辑: 如果我使用萤火虫进入元素,我可以看到正确的“anUniqueIdentifier”。 MyHandler.ashx 总是被调用。我遇到了 photoHandler.ashx 的问题。我添加了随机,但它对我不起作用:

var randomQS = "&Id=" + Math.round(new Date().getTime() / 1000);
//...
$photo.fadeIn('slow');
}).attr('src', myObj.photoSrc + randomQS);

更新:

我解决了,问题是PhotoHandler.ashx,这个控制器正在缓存图片,这样给url添加随机值不起作用。

谢谢。

【问题讨论】:

  • 如果有的话,是浏览器,而不是 jQuery,这是缓存。

标签: jquery image caching ashx


【解决方案1】:

您的浏览器正在缓存您需要通过向其附加随机字符串来破坏缓存的图像:

http://domain.com/myimage.jpg?random=12893128971844

你可以使用 JS math fn 之类的东西:Math.random()

【讨论】:

    【解决方案2】:

    尝试在网址末尾添加时间戳。将 var theTime 放入您的函数中,并将 ? 和 theTime 附加到您的 url。

    var theTime = Math.round(new Date().getTime() / 1000);
    
    var hUrl = "myHandler.ashx?"+theTime;
    

    【讨论】:

      【解决方案3】:

      为图像源添加时间戳:

      ...

      var $photo = $("<img alt='' class='hidden' />").load(function(){
          $("#photo-container").append($photo);
          $photo.fadeIn('slow');
      }).attr('src', myObj.photoSrc + Math.round(new Date().getTime() / 1000));
      

      ...

      【讨论】:

        猜你喜欢
        • 2011-10-29
        • 2012-01-06
        • 2012-01-28
        • 1970-01-01
        • 2020-06-01
        • 2016-06-17
        • 2012-11-29
        • 1970-01-01
        • 2010-12-29
        相关资源
        最近更新 更多