gpt4 book ai didi

javascript - 如果结果是 404 http 错误,则隐藏 iframe(带有 .cgi 源)

转载 作者:行者123 更新时间:2023-12-03 02:08:23 26 4
gpt4 key购买 nike

我想在 html 页面中显示多个 iframe,但如果结果是 404 http 错误,我不想显示此 iframe ($("#iframe").attr("height", "480"); )。我接受所有解决方案(警告:跨域错误)。

我的示例显示 3 个 iframe(第一个是动态的,是我这篇文章的主题)2n 是好的 url,第 3 个是错误的 url (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.

最佳答案

如果结果是 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>

关于javascript - 如果结果是 404 http 错误,则隐藏 iframe(带有 .cgi 源),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49691730/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com