javascript - XMLHttpRequest 连接检查

标签 javascript

我正在尝试编写此处所示的 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/

相关文章:

javascript - Typescript 中的工厂函数使用和不使用 new 关键字声明文件

javascript - CSS 定位元素的方式,无论屏幕大小如何,一次只有元素可见

javascript - 如何使用 Javascript 在 Angular 2 中进行路由

javascript - 尝试使用 Bootstrap 制作模式对话框提示

javascript - php 发送空白电子邮件

javascript - 带按钮的模态缩略图

javascript - 使用 Fetch API 将数据发送到 PHP 服务器(POST 方法和 JSON 首选)

c# - 为什么这个 AJAX 调用需要这么长时间?

javascript - 如何将现代版本的 Vue (Vue CLI3) 与 Electron 结合使用?

JavaScript 说 10 小于 9