我的 MVC3-Webseite 中有图像,它们必须每 30 秒更新一次。因为图像每 30 秒更新一次 im 服务器。所以我尝试用 JQuery 更新它,例如:
<div id="galerie">
<ul>
<li>
<img id = "img1" class = "img1" alt="Image 7" src="@Url.Content("Content/Images/Image_7.jpg")"/>
Image 7
</li>
<li>
<img id = "img2" class = "img2" alt="Image 5" src="@Url.Content("Content/Images/Image_5.jpg")"/>
Image 5
</li>
</div>
<script type="text/javascript">
function UpdateImages() {
$.get('@Url.Action("Details","Display", new { id = "test" } )', function (data) {
$('#main').replaceWith(data);
});
}
function myFunction() {
setInterval(UpdateImages, 30000);
}
</script>
但问题是图片还没有更新。他们需要再次加载页面。不是吗? 所以我想知道如何用 JS 触发 Pageload 事件?还是有其他解决问题的方法? 谢谢你
马雷克 bool 库特
最佳答案
如果图像的 URL 没有改变,浏览器将假定它在缓存中的图像仍然是正确的。
在 JS 中触发重新加载很容易:
document.location.href = document.location.href;
对 href 属性的每次更改都会触发页面重新加载,即使该值未更改也是如此。
为确保图像实际上再次从服务器加载,您可能必须与它们一起发送适当的缓存 header 。
或者,如果您不想重新加载页面而只是替换图像,您可以将随机参数附加到图像 URL:../image1.jpg?p=121799595
这将强制浏览器查询服务器。
编辑:或者,您可以通过 MVC 操作传递图像以确保每次都能获得新副本:
public FileStreamResult StreamImage(string fileName)
{
// todo: Check whether the file actually exists and is an image
string path = AppDomain.CurrentDomain.BaseDirectory + "images/";
return File(new FileStream(path + fileName, FileMode.Open), "image/jpeg", fileName);
}
关于javascript - 我如何更新我的 MVC 3 站点中的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13191806/