在 AJAX 中,使用 XMLHttpRequest(XHR)对象发送请求是实现异步通信的基本方法。以下是一个简单的例子,演示如何使用 XHR 发送一个 GET 请求:
// 创建 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();

// 配置请求:指定请求的类型和URL,以及是否异步
xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);

// 设置回调函数,处理请求完成后的操作
xhr.onload = function() {
  if (xhr.status === 200) {
    // 请求成功,处理响应数据
    console.log('Response:', xhr.responseText);
  } else {
    // 请求失败,处理错误信息
    console.error('Request failed. Status:', xhr.status);
  }
};

// 设置请求发生错误时的回调函数
xhr.onerror = function() {
  console.error('Network error occurred');
};

// 发送请求
xhr.send();

上述代码分为几个步骤:

1. 创建 XMLHttpRequest 对象: 使用 new XMLHttpRequest() 创建一个 XMLHttpRequest 对象。

2. 配置请求: 使用 open 方法配置请求的类型(GET、POST 等)、URL(要请求的服务器地址)以及是否采用异步模式(true 表示异步,false 表示同步)。

3. 设置回调函数: 使用 onload 事件处理请求成功完成后的操作,使用 onerror 事件处理请求发生错误时的操作。onload 事件在请求成功完成时触发,onerror 事件在请求发生错误时触发。

4. 发送请求: 使用 send 方法发送请求。对于 GET 请求,可以不传递参数;对于 POST 请求,通常需要传递请求体(body)。

在实际应用中,你可能会发送包含数据的 POST 请求,处理更多的状态码,使用异步操作进行页面更新等。下面是一个使用 POST 请求的例子:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://jsonplaceholder.typicode.com/posts', true);
xhr.setRequestHeader('Content-Type', 'application/json');

xhr.onload = function() {
  if (xhr.status === 201) {
    console.log('Post created. Response:', xhr.responseText);
  } else {
    console.error('Request failed. Status:', xhr.status);
  }
};

xhr.onerror = function() {
  console.error('Network error occurred');
};

var postData = JSON.stringify({
  title: 'New Post',
  body: 'This is the content of the new post.',
  userId: 1
});

xhr.send(postData);

在这个例子中,我们创建了一个包含 JSON 数据的 POST 请求,并设置了请求头的 Content-Type。在 xhr.send(postData) 中,我们将 JSON 数据发送给服务器。根据服务器的处理逻辑,你可能需要调整请求体的格式和内容。


转载请注明出处:http://www.zyzy.cn/article/detail/13180/AJAX