AJAX - 使用 XMLHttpRequest 的命令顺序(新手)

发布于 2025-01-08 12:47:59 字数 472 浏览 0 评论 0原文

在我在互联网上找到的大多数示例中,我看到这样的内容:

ajaxRequest.onreadystatechange = function() {   
    if(ajaxRequest.readyState == 4) {
        document.myForm.time.value = ajaxRequest.responseText;
    }
}

ajaxRequest.open("GET", "serverTime.php", true);
ajaxRequest.send(null);

当“更改状态”时,这怎么可能以及此代码如何工作 属性已检查 之前 执行打开和发送命令? 我知道它有效......但是流程如何返回到“检查状态” 执行“打开”和“发送”后的“状态”。

感激任何帮助,非常感谢:-)

我将不胜

In most examples I found on the Internet , I see something like this :

ajaxRequest.onreadystatechange = function() {   
    if(ajaxRequest.readyState == 4) {
        document.myForm.time.value = ajaxRequest.responseText;
    }
}

ajaxRequest.open("GET", "serverTime.php", true);
ajaxRequest.send(null);

How is it possible and how does this code work , when the "change state"
property is checked
BEFORE
the open and send commands are executed ?
I know it works...but how does the flow return back to "check the state
status" after the "open" and "send" are executed.

I would appreciate any help

Many thanks in advance :-)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

远山浅 2025-01-15 12:47:59

因为 onreadystatechange 是一个事件,并且在就绪状态更改之前不会调用该代码,这将在请求完成后的某个时刻发生。

Because onreadystatechange is an event, and that code won't get invoked until the ready state changes, which will occur at some point in the future when the request is complete.

没︽人懂的悲伤 2025-01-15 12:47:59

这正是 AJAX 的流程

发出请求

您已经有了闪亮的新 XMLHttpRequest 对象;现在试一试。首先,您需要一个 Web 页面可以调用的 JavaScript 方法(例如当用户键入文本或从菜单中选择一个选项时)。然后,您将在几乎所有 Ajax 应用程序中遵循相同的基本轮廓:

  1. 从 Web 表单获取所需的任何数据。
  2. 构建要连接的 URL。
  3. 打开与服务器的连接。
  4. 设置一个函数,以便服务器在完成后运行。
  5. 发送请求。

处理响应

现在您需要实际处理服务器的响应。此时您实际上只需要知道两件事:

* Don't do anything until the xmlHttp.readyState property is equal to 4.
* The server will stuff it's response into the xmlHttp.responseText property.

This is exactly the flow of AJAX

Making a request

You have your shiny new XMLHttpRequest object; now take it for a spin. First, you need a JavaScript method that your Web page can call (like when a user types in text or selects an option from a menu). Then, you'll follow the same basic outline in almost all of your Ajax applications:

  1. Get whatever data you need from the Web form.
  2. Build the URL to connect to.
  3. Open a connection to the server.
  4. Set up a function for the server to run when it's done.
  5. Send the request.

Handling the response

Now you need to actually deal with the server's response. You really only need to know two things at this point:

* Don't do anything until the xmlHttp.readyState property is equal to 4.
* The server will stuff it's response into the xmlHttp.responseText property.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文