为什么我的脚本在调用XMLHttpRequest.send()后停止运行

Why does my script stop running after calling XMLHttpRequest.send()?

本文关键字:运行 send 脚本 我的 调用 XMLHttpRequest 为什么      更新时间:2023-09-26

我正试图掌握XMLHttpRequest()对象的工作原理。

如果我删除xhr.send(), "hi"将显示。但当它存在时,什么也显示不出来。我真的想把xhr.status写到屏幕上,但首先我需要知道为什么脚本没有完成执行,即使其余部分不依赖于xhr.send()之后的响应。

<html>
    <head>
        <title>Playground</title>
    </head>
    <body>
        <div>
            <script>
                var xhr = new XMLHttpRequest();
                xhr.open("GET","http://www.google.com",false);
                xhr.send();
                document.write("hi");
            </script>
        </div>
    </body>
</html>

XMLHttpRequest可作为同步和异步,第三个参数传入函数设置此模式。传递false意味着设置为同步,例如wait till call finished

改为:

 var xhr = new XMLHttpRequest();
                xhr.open("GET","http://www.google.com",true);
                xhr.send();
                document.write("hi");

应该写为"hi"或者你可以完全删除第三个参数默认为异步

 var xhr = new XMLHttpRequest();
                    xhr.open("GET","http://www.google.com");
                    xhr.send();
                    document.write("hi");

您不能向http://www.google.com发出XHR请求,因为它是不同的来源。如果您打开开发控制台,您可能会看到如下错误:

Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': 
Failed to load 'http://www.google.com/'. 

为了发出一个AJAX请求,被请求的域、端口和协议必须与源匹配。

由于脚本的这一行抛出了一个错误,并且调用被设置为不是异步的(如LIUFA所述),下一行将不会被执行。