我希望在html页面中显示多个iframe,但如果结果是404 http错误,我不想显示此iframe($("#iframe").attr("height", "480");
)。我接受所有解决方案(警告:跨域错误)。
我的示例显示3个iframe(第一个是动态的,是我这个帖子的主题)2n是好网址,第3个是错误的网址(http 404)。
代码:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<iframe id="iframe" src="" width="0" height="0"></iframe>
<iframe src="http://xxx.xxx.xxx.20:81/script.cgi" width="640" height="480"></iframe>
<iframe src="http://xxx.xxx.xxx.21:81/script.cgi" width="640" height="480"></iframe>
<script>
$(function() {
$.ajax({
url: "http://xxx.xxx.xxx.21:81/script.cgi",
dataType: "jsonp",
timeout: 5000,
success: function () {
$("#iframe").attr("src", "http://xxx.xxx.xxx.21:81/script.cgi");
$("#iframe").attr("width", "640");
$("#iframe").attr("height", "480");
}
});
});
</script>
</body>
</html>
我尝试其他解决方案但不起作用:
<iframe id="iframe" src="" width="0" height="0"></iframe>
<script>
$("#iframe").attr("src", "http://xxx.xxx.xxx.21:81/script.cgi");
if($("#iframe").contents().find("body").length) {
$("#iframe").attr("width", "640");
$("#iframe").attr("height", "480");
}
</script>
我尝试删除dataType: "jsonp",
但不起作用:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
答案 0 :(得分:1)
如果结果为404 http错误
,您可以使用此代码隐藏div
$(function () {
$.ajax({
url: "https://www.googleapis.com/youtube/v3/videos?id=tgbNymZ7vqY",
dataType: "jsonp",
timeout: 5000,
success: function () {
$("#iframe").attr("src", "https://www.youtube.com/embed/tgbNymZ7vqY");
$("#iframe").attr("width", "640");
$("#iframe").attr("height", "480");
},
error: function (xhr, responseText) {
if (xhr.status == 404) {
console.log(xhr.status)
$("#iframe").hide();
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<iframe id="iframe" src="" width="0" height="0"></iframe>
<iframe src="http://xxx.xxx.xxx.20:81/script.cgi" width="640" height="480"></iframe>
<iframe src="http://xxx.xxx.xxx.21:81/script.cgi" width="640" height="480"></iframe>