如果我请求一个在目录中找不到的文件,我得到的错误状态代码为 404,而不是显示 404 错误页面,我只想在 div/警报/显示图像中保留一些文本
<script>
$.ajax({ cache: false,
url: "basic1.css",
data: { },
success: function (data) {
$('#id').html(data);
},
error:function (xhr, ajaxOptions, thrownError){
if(xhr.status==404) {
//alert(thrownError);
alert("the requested page not found");
}
}
});
</script>
在上面的代码中,我想获得一个警报而不是错误页面,并且它直接显示错误(404)对象未找到页面。
如何限制显示 404 错误页面?
最佳答案
请在错误处理程序中插入以下代码
<script>
$.ajax({ cache: false,
url: "basic1.css",
data: { },
success: function (data) {
$('#id').html(data);
},
error:function (xhr, ajaxOptions, thrownError){
if(jqXHR.status == 404 || thrownError == 'Not Found') {
$('#id').html("<img src='imagelink-here'/>"); // If you want to show an image
$('#id').html("Sorry, the page is not found"); // if you need text
}
}
});
</script>
此外,请确保 ajax 请求的基本 URL 正确。
根据上面的代码,向以下 URL 发出 ajax 请求
http://domain.com/basic1.css
因此请确保添加正确的基本 url 和路径。
关于javascript - 如果发生页面 404 错误,则显示警报或图像而不是错误页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23515967/