javascript - 无法通过 JQuery 更改图像的 src

标签 javascript c# jquery ajax asp.net-mvc

我正在开发 ASP.NET MVC 4 应用程序。我试图在 Controller 将数据发送到 View 后更改 src 属性,但是我所有的尝试都没有结果。 View 中的脚本:

<script type="text/javascript">
$(document).ready(function () {
    $('#fileupload').fileupload({
        dataType: 'json',
        url: '/Home/UploadFiles',
        autoUpload: true,
        done: function (e, data) {
            $('.file_name').html(data.result.name);
            $('.file_type').html(data.result.type);
            $('.file_size').html(data.result.size);             
            $('.file_source').attr('src', 'D:/somePhoto.jpg'); //this row does not set 'src' of <img/>
        }
    }).on('fileuploadprogressall', function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $('.progress .progress-bar').css('width', progress + '%');
    });
});
</script>

<img class="file_source" src="" /> <!--src attribute is just empty---> 

你能告诉我哪里出错了吗? 此行不起作用:

$('.file_source').attr('src', 'D:/somePhoto.jpg'); //this row does not set 'src' of <img/>

标签的属性“src”未更改为 src="D:/somePhoto.jpg"。 任何帮助将不胜感激。

最佳答案

您是否尝试过在图像源内从网络分配有效的图像位置?我很确定,D:\somePhoto.jpg 是服务器端的位置。如果是这样的话,那么 javscript 不知道如何获取它,因为 js 运行在客户端,当你已经从 Controller 发送数据后,有它无能为力。

首先使用网络上提供的图像进行测试,例如 - http://sci8.com/wp-content/uploads/2014/10/test-all-the-things.jpg

因此将您的代码更改为 -

$('.file_source').attr('src', 'http://sci8.com/wp-content/uploads/2014/10/test-all-the-things.jpg');

如果这有效(我很确定它会有效),那么您就知道原因了。只需将 somePhoto.jpg 保存在项目的 Content 文件夹中的某个位置并使用该 url。

例如

$('.file_source').attr('src', 'http://<hostaddress>/content/image/somePhoto.jpg');

如果您仍然遇到问题,请告诉我。

关于javascript - 无法通过 JQuery 更改图像的 src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29369506/

相关文章:

javascript - 在网页刷新时增加变量的变量值

c# - 通过网络访问 sql server 数据库 2008 r2 时出现问题

javascript - 使用逗号值作为饼图中的数据点

jquery - 如何在网络驱动程序中检查页面是否已完全加载?

javascript - Firefox 在 jquery AJAX 发布时在 URL 中显示表单数据

javascript - 如何在 extjs 网格单元中显示嵌套数组

Javascript:如何直接从对象生成格式化的易于阅读的 JSON?

c# - 互操作 C# 到 C++ 结构

c# - C#中调用方法语法时赋值

jquery - 使用 jQuery 在元素后插入表格