我正在尝试编写此处所示的 XMLHttpRequest 演示脚本的简化版本:
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
我只会在 iPad 上使用它,因此我不必检查旧版本的 IE 等。单击按钮时,我想检查连接是否存在。这是我的整个 html 页面,包括 JavaScript 片段:
<html>
<head>
<script>
var myURL = "http://www.google.com";
function testConnection(url) {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert("Connected!");
} else {
alert("Not connected!");
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
</head>
<body>
<button type="button" onclick="testConnection(myURL)">Test Connection</button>
</body>
</html>
出于某种奇怪的原因,即使我在线,当我单击按钮时,我也会重复收到“未连接”警报,并且过了一会儿我才收到“已连接”警报,然后就没有警报了。
看起来我搞砸了,但我看不出哪里。我应该改变什么才能让它发挥作用?
最佳答案
如果你可以使用xhr2 ,你可以从this tutorial学习东西并将您的代码重写为如下所示:
function testConnection(url) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() { alert("Connected!"); }
xmlhttp.onerror = function() { alert("Not Connected"); }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
如果您将请求发送到另一个域,如果目标服务器具有相同域策略限制(默认),即使该域存在,您也可能会收到错误。如果目标服务器位于另一个域,则必须发送 header
Access-Control-Allow-Origin: *
关于javascript - XMLHttpRequest 连接检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17347764/