租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

ajax、axios与fetch如何调用后台api

发布时间:2023-10-21 16:26:31

ajax、axios与fetch如何调用后台api

使用Ajax调用后台API:

$.ajax({
  url: "your-api-url",
  type: "GET/POST/PUT/DELETE",
  dataType: "json", // 根据后台返回的数据类型决定,可以是json、xml、html等
  data: { // 可选,发送到服务器的数据,可以是对象、字符串或数组
    param1: value1,
    param2: value2
  },
  success: function(response) {
    // 要求成功后的处理逻辑
    console.log(response);
  },
  error: function(xhr, status, error) {
    // 要求失败后的处理逻辑
    console.log(xhr.responseText);
  }
});

使用Axios调用后台API:

axios({
  method: "GET/POST/PUT/DELETE",
  url: "your-api-url",
  params: { // 可选,发送到服务器的查询参数,可以是对象
    param1: value1,
    param2: value2
  },
  data: { // 可选,发送到服务器的要求体数据,可以是对象
    param1: value1,
    param2: value2
  }
})
  .then(function(response) {
    // 要求成功后的处理逻辑
    console.log(response.data);
  })
  .catch(function(error) {
    // 要求失败后的处理逻辑
    console.log(error.response.data);
  });

使用Fetch调用后台API:

fetch("your-api-url", {
  method: "GET/POST/PUT/DELETE",
  headers: {
    "Content-Type": "application/json" // 根据后台要求的数据类型决定,可以是application/json、application/xml等
  },
  body: JSON.stringify({ // 可选,发送到服务器的要求体数据,需要将对象转换为JSON字符串
    param1: value1,
    param2: value2
  })
})
  .then(function(response) {
    // 要求成功后的处理逻辑
    return response.json(); // 解析响应数据为JSON
  })
  .then(function(data) {
    console.log(data);
  })
  .catch(function(error) {
    // 要求失败后的处理逻辑
    console.log(error);
  });

注意:以上代码中的"your-api-url"需要替换为实际的后台API地址。