我html从请求到我的自制服务器返回一个简单的页面:
<html>
<head>
<title>Server Sample</title>
</head>
<img src="/stream.jpeg">
</html>
Run Code Online (Sandbox Code Playgroud)
要img在页面中呈现图像,在路径/stream.jpeg下向服务器发出第二个请求以获取实际图像数据.但是,如果此请求由于某些原因而失败,我想向用户显示错误页面或某种消息.从失败请求的上下文重定向或生成html错误页面似乎不起作用,可能是因为初始页面需要图像.在这种情况下,页面显示"空"img标记而不是想要的错误.
解决这个问题最便携的方法是什么?如果可能的话,我更喜欢使用html解决方案,但也允许使用javascript.
请注意,我编写的服务器非常简单,动态生成非常简单的页面,它不是复杂服务器可以提供的那种扩展.
试试这个:
<img src="stream.jpeg" onerror="errorFunction();">
Run Code Online (Sandbox Code Playgroud)
但onerror属性包含在HTML5中.所以在旧的HTML中会失败.
JavaScript的:
function errorFunction() {
// Here you implement what's happening if the image failed to load.
// For example:
window.location.assing('http://my-site/error-page.html');
// or
console.log('Sorry, but image cannot be loaded right now.');
}
Run Code Online (Sandbox Code Playgroud)
必须在<img>标记之前定义此函数.否则,如果在定义函数之前图像无法加载,HTML将无法找到此函数,您将收到引用错误.