使用ajax()jquery函数的异步调用从缓存显示图像

时间:2012-02-01 08:03:13

标签: jquery asp.net ajax caching

对于我的项目,我希望通过ajax()jquery函数的异步调用动态显示缓存的图像。

$.ajax({
    type: “POST”,
    url: “mypage.aspx/GetThumbnail”,
    data: “{‘id’:'" + idThumbnail + "’}”,
    contentType: “application/json; charset=utf-8?,
    dataType: “json”,
    success: function(msg) {
       // Hide the fake progress indicator graphic.
       $('#thumbnailContent').removeClass('loading');

       // Insert the returned HTML into the <div>.
       $('#thumbnailContent').html(msg.d);
    }
});

这个JQuery块代码将异步调用“mypage.aspx”页面的静态web方法“GetThumbnail”,如果成功,那么我的webmethod的返回将显示为html,如下所示:

<img url="myThumbnailImage.jpg" />

我的问题来自静态webmethod,它应该在字符串上返回格式化的html,但是当我从缓存中读取数据时,我会像这样恢复byte []:

if (HttpContext.Current.Cache[id_thumbnail+ "_thumbnail"] != null)
  {
  byte[] mytemptabbyte = (byte[])HttpContext.Current.Cache[id_thumbnail + "_thumbnail"];
  HttpContext.Current.Response.Clear();
  HttpContext.Current.Response.AddHeader("Content-Type", "image/jpeg");
  HttpContext.Current.Response.Write("");
  HttpContext.Current.Response.BinaryWrite(mytemptabbyte);
  HttpContext.Current.Response.Flush();
  HttpContext.Current.Response.End();
  }

如何使用我的缓存图像返回html格式的响应?

编辑:

所以我称之为新的aspx页面,我可以这样做吗?

function LoadThumnail(id_thumbnail){
  $.ajax({
    type: “POST”,
    url: “getThumbnail.aspx?id_thumbnail=”id_thumbnail,
    data: “{}”,
    contentType: “application/json; charset=utf-8?,
    dataType: “json”,
    success: function(msg) {

       // Insert the returned HTML into the <div>.
       $('#thumbnailContent').html('<img src="' + msg.d + '" />);

       // Hide the fake progress indicator graphic.
       $('#thumbnailContent').removeClass('loading');
    }
});

}

1 个答案:

答案 0 :(得分:0)

创建一个页面(例如getimage.aspx),并将您调用的代码“从缓存中获取图像”放置到该页面的OnInit / Page_Init。

然后,让IMG标签是这样的:

<img url="getimage.aspx?id=myThumbnailImage.jpg" />

<img url="getimage.aspx?id=1234" />

然后,同时阅读Request.QueryString["id"]并使用它来从缓存中检索图像。