?Briella 2014-03-05 20:14 采纳率: 0%
浏览 37

使用AJAX显示图像

I am trying to display a picture that I am calling from the controller using AJAX, this is my code:

<div id="productImg" style="display:none;">

</div>


<script>
    function showPic(id) {

        $.ajax({
            type: "GET",
            url: "/Equipment/GetImage",
            data: { 'productId': id },
            success: function (data) {
                $("#productImg").html(data)

            }
        });
</script>

And the method on my controller looks like this:

public virtual FileContentResult GetImage(int productId) {
  Product prod = _db.Products.FirstOrDefault(p => p.ProductID == productId);
  if (prod != null) {
    return File(prod.ImageData, prod.ImageMimeType);
  } else {
    return null;
  }
}

What I am getting is a lot of code and not the image. What else could I try?

  • 写回答

2条回答 默认 最新

  • Lotus@ 2014-03-05 20:18
    关注

    You don't need to use AJAX for this. Images are separate resources for a page and are loaded as separate requests already. Just link to it:

    <div id="productImg">
        <img src="/Equipment/GetImage?productId=123" alt="Product" />
    </div>
    

    For making that happen dynamically in JavaScript, all you need to do is change that src value:

    function showPic(id) {
        $('#productImg img').src = '/Equipment/GetImage?productId=' + id;
    }
    

    As an aside, the reason your approach doesn't work is because what you're getting back from the server isn't HTML, it's the raw image data. The HTML to display an image is not the image data itself, it's just an img tag with a URL. (That URL can contain an encoded copy of the actual data, but it really doesn't need to in this case.)

    评论

报告相同问题?

悬赏问题

  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站