?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.)

    评论

报告相同问题?

悬赏问题

  • ¥15 Coze智能助手搭建过程中的问题请教
  • ¥15 12864只亮屏 不显示汉字
  • ¥20 三极管1000倍放大电路
  • ¥15 vscode报错如何解决
  • ¥15 前端vue CryptoJS Aes CBC加密后端java解密
  • ¥15 python随机森林对两个excel表格读取,shap报错
  • ¥15 基于STM32心率血氧监测(OLED显示)相关代码运行成功后烧录成功OLED显示屏不显示的原因是什么
  • ¥100 X轴为分离变量(因子变量),如何控制X轴每个分类变量的长度。
  • ¥30 求给定范围的全体素数p的(p-2)/p的连乘积值
  • ¥15 VFP如何使用阿里TTS实现文字转语音?