在iframe中显示之前使用javascript检测url是否存在 [英] using javascript to detect whether the url exists before display in iframe

查看:13
本文介绍了在iframe中显示之前使用javascript检测url是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 javascript 将动态 url 传递给 iframe src.但有时 url 不存在,我怎么能事先检测到不存在的 url,以便我可以隐藏带有 404 错误的 iframe.

I'm using javascript to pass a dynamic url to iframe src. but sometimes the url does not exist, how could i detect the non-exist url beforehand, so that i can hide the iframe that with 404 error.

推荐答案

由于我名声低,我无法评论德里克我会功夫的回答.我已经尝试过该代码,但效果不佳.Derek 朕会功夫的密码共有三个问题.

Due to my low reputation I couldn't comment on Derek 朕會功夫's answer. I've tried that code as it is and it didn't work well. There are three issues on Derek 朕會功夫's code.

  1. 第一个是异步发送请求并更改其属性状态"的时间比执行下一个表达式 - if(request.status === "404") 慢.因此 request.status 最终将由于互联网带宽而保持状态 0(零),并且它不会实现下面的代码.解决这个问题很简单:在 ajax 请求的方法 open 上将true"更改为false".这将导致您的代码出现短暂(或不是)阻塞(由于同步调用),但会在到达 if 测试之前更改请求的状态.

  1. The first is that the time to async send the request and change its property 'status' is slower than to execute the next expression - if(request.status === "404"). So the request.status will eventually, due to internet band, remain on status 0 (zero), and it won't achieve the code right below if. To fix that is easy: change 'true' to 'false' on method open of the ajax request. This will cause a brief (or not so) block on your code (due to synchronous call), but will change the status of the request before reaching the test on if.

二是状态为整数.使用 '===' javascript 比较运算符,您尝试比较左侧对象是否与右侧对象相同.要完成这项工作,有两种方法:

The second is that the status is an integer. Using '===' javascript comparison operator you're trying to compare if the left side object is identical to one on the right side. To make this work there are two ways:

  • 去掉404周围的引号,使其成为整数;
  • 使用 javascript 的运算符==",以便您测试两个对象是否相似.

第三个是对象 XMLHttpRequest 仅适用于较新的浏览器(Firefox、Chrome 和 IE7+).如果您希望该代码段适用于所有浏览器,您必须按照 W3Schools 建议的方式进行操作:w3schools ajax

The third is that the object XMLHttpRequest only works on newer browsers (Firefox, Chrome and IE7+). If you want that snippet to work on all browsers you have to do in the way W3Schools suggests: w3schools ajax

真正对我有用的代码是:

The code that really worked for me was:

var request;
if(window.XMLHttpRequest)
    request = new XMLHttpRequest();
else
    request = new ActiveXObject("Microsoft.XMLHTTP");
request.open('GET', 'http://www.mozilla.org', false);
request.send(); // there will be a 'pause' here until the response to come.
// the object request will be actually modified
if (request.status === 404) {
    alert("The page you are trying to reach is not available.");
}

这篇关于在iframe中显示之前使用javascript检测url是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆