這是我的JavaScript代碼,它每10秒鐘ping Google,並顯示連接狀態到html MonitorInformation元素。但是當我單擊html文件進行調試時,顯示在MonitorInformation元素上的信息始終爲「正在連接...等待」。我調試了一段時間,但無法弄清楚。任何想法我的代碼有什麼問題?javascript連接到網站代碼不工作
HTML代碼:
<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腳本代碼:
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
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>
由於事先 喬治
我修復
JSON無法正常工作,您需要使用JSONP,它只在您正在訪問的服務提供時纔有效。 – FlySwat 2009-07-26 14:28:16
我很困惑FlySwat,但是我在使用JSON的EDIT 1部分中發佈了代碼。任何意見? – George2 2009-07-26 14:29:56