JavaScript的连接到网站code不工作 [英] javascript connect to web site code not working
问题描述
下面是我的javascript code的平谷歌每10秒,并显示连接状态为html MonitorInformation元素。但是,当我点击HTML文件进行调试,在MonitorInformation元素显示的信息始终是连接...等待。我已经调试了一段时间,但无法弄清楚。任何想法有什么不对我的code?
Here is my javascript code which ping Google for every 10 seconds and display the connection status to html MonitorInformation element. But when I click the html file to debug, the information displayed at MonitorInformation element is always "Connecting...wait". I have debugged for some time but can not figure out. Any ideas what is wrong with my code?
的Html code:
Html code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="Monitor.js" type="text/javascript"></script>
<title>Web Site Monitor</title>
</head>
<body onload="setup()">
<div id="MonitorInformation">Connecting...wait</div>
</body>
</html>
Java脚本的code:
Java script code:
function setup() {
window.setInterval(PingWebSite, (10 * 1000));
}
function PingWebSite() {
conObj = new ActiveXObject("Msxml2.XMLHTTP");
conObj.open("GET", "http://www.google.com", true);
conObj.onreadystatechange = function() {
if (conObj.readyState === 4) {
if (conObj.status === 200) {
loading.innerText = "Service is available";
} else {
MonitorInformation.innerText = "Service is not available";
}
} else {
MonitorInformation.innerText = "Connecting to www.google.com ...";
}
}
}
编辑1:使用JSON我修复
EDIT 1: my fix using JSON
function setup() {
window.setInterval(PingWebSite, (10 * 1000));
}
function PingWebSite() {
var http_request = new XMLHttpRequest();
http_request.open("GET", "http://www.google.com", true);
http_request.send(null);
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
MonitorInformation.innerText = "Connection ok";
alert("ok");
} else {
MonitorInformation.innerText = "Connection fail";
alert("fail");
}
http_request = null;
}
};
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="Monitor.js" type="text/javascript"></script>
<title>Web Site Monitor</title>
</head>
<body onload="setup()">
<div id="MonitorInformation">Connecting...wait</div>
</body>
</html>
在此先感谢, 乔治
thanks in advance, George
推荐答案
您无法连接到网站网址之外。除非你的code是在google.com域名将无法正常工作。
You can't connect to a site outside of your URL. Unless your code is on the google.com domain it won't work.
这是一个名为同根同源政策浏览器安全项目 http://en.wikipedia.org/维基/ Same_origin_policy
This is a browser security item called 'Same origin policy' http://en.wikipedia.org/wiki/Same_origin_policy
如果你想要做跨站点调用,例如,你将不得不使用JSONP 的http:// EN。 wikipedia.org/wiki/JSON 的作为,可以让你做到这一点。
If you want to do cross site calls like that you will have to use JSONP http://en.wikipedia.org/wiki/JSON as that lets you do that.
这篇关于JavaScript的连接到网站code不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!