XML HttpRequest

所有现代浏览器都有内置的 XMLHttpRequest 对象,用于从服务器请求数据。

XMLHttpRequest 对象

XMLHttpRequest 对象可用于从 Web 服务器请求数据。

XMLHttpRequest 对象是开发者的梦想,因为您能够:

  • 更新网页 - 在不重新加载页面的情况下
  • 从服务器请求数据 - 在页面已加载后
  • 从服务器接收数据 - 在页面已加载后
  • 向服务器发送数据 - 在后台

XMLHttpRequest 实例

当您在下面的输入字段中键入字符时,XMLHttpRequest 会被发送到服务器,并返回一些名字建议(从服务器):

实例

请在下面的输入字段中输入名字:

Name: Suggestions: 本教程的 AJAX 章节中对上面的示例进行了解释。

发送 XMLHttpRequest

下面是使用 XMLHttpRequest 对象的常见 JavaScript 语法:

实例

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Typical action to be performed when the document is ready:
       document.getElementById("demo").innerHTML = xhttp.responseText;
    }
};
xhttp.open("GET", "filename", true);
xhttp.send();

亲自试一试

例子解释

上面的例子中的第一行创建了一个 XMLHttpRequest 对象

var xhttp = new XMLHttpRequest();

onreadystatechange 属性指定每次 XMLHttpRequest 对象的状态发生变化时要执行的函数:

xhttp.onreadystatechange = function()

readyState 属性为 4 且 status 属性为 200 时,响应就绪:

if (this.readyState == 4 && this.status == 200)

responseText 属性以文本字符串形式返回服务器响应。

文本字符串可用于更新网页:

document.getElementById("demo").innerHTML = xhttp.responseText;

您将在本教程的 AJAX 章节中学到有关 XMLHttpRequest 对象的更多内容。