Asp.net mvc - 使用jquery替换图像

时间:2014-05-19 12:47:57

标签: jquery asp.net-mvc image

我有一个带图片的页面。我想首先显示一个加载gif,然后使用Ajax更改图像src ...

我找到了this。这是我的代码:

                    @{
                    if (Model.HavePhoto)
                    {
                        <img id="userPhoto" src="~/Content/images/ajax-loader.gif" align="right" class="user-img" />
                        <script>
                            $.ajax({
                                url: '@Url.Action("GetPersonPhoto", "Home")',
                                data: { name: "personName" },
                                cache: false,
                                type: "POST",
                                dataType: "image/png",
                                success: function (data) {
                                    $('#userPhoto').attr('src', data);
                                },
                                error: function (xhr, status, error) {
                                    alert(xhr.status);
                                }
                            });
                        </script>
                    }

                    else
                    {
                        <img id="userPhoto" src="~/Content/images/header-default_user.png" align="right" class="user-img" />
                    }
                }

我的GetPersonPhoto方法直接返回图片:

return File(photo, "image/png");

但是我的Ajax调用不起作用,我收到一封emtpy错误消息,状态为&#34; 200&#34; ...

使用DataType肯定是一种错误的方法或问题......我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

您可以使用图片的onload事件。

使用

<img id="userPhoto" src="~/Content/images/ajax-loader.gif" align="right" class ="user-img" />
<script>
    var img = new Image();
    img.src = '@Url.Action("GetPersonPhoto", "Home" , new { "name" = "personName" })';
    img.onload = function () {
        $('#userPhoto').attr('src', this.src);
    }; 
</script>