VUE——Ajax【请求方式】

一、XMLHttpRequest 示例

1. GET 请求(获取数据)

// 创建对象
const xhr = new XMLHttpRequest();

// 配置请求(异步GET)
xhr.open('GET', 'https://api.example.com/users/123', true);

// 设置响应类型为 JSON(可选)
xhr.responseType = 'json';

// 监听请求状态变化
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) { // 请求完成
    if (xhr.status === 200) {
      const user = xhr.response; // 自动解析为 JSON 对象(因设置了 responseType)
      console.log('用户数据:', user);
    } else {
      console.error('请求失败,状态码:', xhr.status);
    }
  }
};

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

2. POST 请求(提交数据)

const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/users', true);

// 设置请求头信息(告诉服务器发送的是 JSON)
xhr.setRequestHeader('Content-Type', 'application/json');

// 准备要提交的数据
const newUser = { name: 'Alice', age: 25 };
const jsonData = JSON.stringify(newUser);

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 201) { // 201表示资源已创建
    console.log('用户已创建:', xhr.response);
  }
};

// 发送数据(在send()中传递)
xhr.send(jsonData);

3. PUT 请求(更新数据)

const xhr = new XMLHttpRequest();
xhr.open('PUT', 'https://api.example.com/users/123', true);
xhr.setRequestHeader('Content-Type', 'application/json');

const updatedUser = { age: 26 };
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log('用户已更新:', xhr.response);
  }
};

xhr.send(JSON.stringify(updatedUser));  //网络传递过程中要以字符串形式传递

4. DELETE 请求(删除数据)

const xhr = new XMLHttpRequest();
xhr.open('DELETE', 'https://api.example.com/users/123', true);

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 204) { // 204表示无内容(删除成功)
    console.log('用户已删除');
  }
};

xhr.send();

1. 请求头设置
Content-Type: 必须与发送的数据格式匹配(如 application/json)
自定义头(如身份验证):

xhr.setRequestHeader('Authorization', 'Bearer your_token'); // XMLHttpRequest
headers: { 'Authorization': 'Bearer your_token' }

2. 异步 vs 同步
XMLHttpRequest: 第三个参数 open(method, url, async),建议永远用 true(异步)。

3. 错误处理
XMLHttpRequest: 监听 onerror 和检查 status。

4. 跨域请求(CORS)
需服务器设置响应头(如 Access-Control-Allow-Origin: *)。
涉及复杂请求(如自定义头)时,浏览器会先发送 OPTIONS 预检请求。
四、总结
XMLHttpRequest 是传统方案,适合兼容旧浏览器。

你可能感兴趣的:(VUE疑难杂症,vue.js,ajax,前端)