GET和POST是HTTP协议中的两种发送请求的方法,每种方法都有自己的特点和用途。
- 参数位置:GET方法的参数是放在URL中的,而POST方法的参数是放在HTTP请求的Body中的。
 - 数据传输:GET方法的URL长度有限制(通常限制在2048个字符),而POST方法的数据大小没有限制。
 - 缓存问题:GET方法的请求是可缓存的,而POST方法的请求通常不可缓存。
 - 编码类型:GET方法通常只能发送ASCII字符,而POST方法没有这个限制。
 - 参数暴露:GET方法的参数是暴露在URL中的,可以在浏览器的历史记录中看到,而POST方法的参数则不会显示出来。
 - 应用场景:GET方法适合于无副作用的请求,即只读取服务器上的数据,不会修改服务器上的数据;POST方法适合于有副作用的请求,即会修改服务器上的数据。
 
Ajax请求通常使用JavaScript中的XMLHttpRequest对象或Fetch API来发送HTTP请求。以下是使用这两种方式发送GET和POST请求的示例代码:
使用XMLHttpRequest发送GET请求:
var xhr = new XMLHttpRequest();
xhr.open("GET", "your-api-endpoint?param1=value1¶m2=value2", true);
xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && xhr.status == 200) {
    console.log(xhr.responseText);
  }
};
xhr.send();使用XMLHttpRequest发送POST请求:
var xhr = new XMLHttpRequest();
xhr.open("POST", "your-api-endpoint", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && xhr.status == 200) {
    console.log(xhr.responseText);
  }
};
xhr.send("param1=value1¶m2=value2");使用Fetch API发送GET请求:
fetch("your-api-endpoint?param1=value1¶m2=value2")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log("Error:", error));使用Fetch API发送POST请求:
fetch("your-api-endpoint", {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: new URLSearchParams({ param1: 'value1', param2: 'value2' })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log("Error:", error));在这些示例中,替换your-api-endpoint为你的API端点,param1和param2为你要发送的参数的键和值。