在 JS 中如何使用 Ajax 来进行请求
    		       		warning:
    		            这篇文章距离上次修改已过441天,其中的内容可能已经有所变动。
    		        
        		                
                在JavaScript中,可以使用原生的XMLHttpRequest对象或者现代的fetch API来实现Ajax请求。以下是使用XMLHttpRequest和fetch的示例代码。
使用 XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open("GET", "your-api-endpoint", true);
xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && xhr.status == 200) {
    // 请求成功
    var response = xhr.responseText;
    console.log(response);
  }
};
xhr.send();使用 fetch (适用于现代浏览器):
fetch("your-api-endpoint")
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok ' + response.statusText);
    }
    return response.text();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
  });在这两个示例中,替换your-api-endpoint为你需要请求的API端点。使用fetch的代码是基于Promise的,更加现代和简洁。如果你需要支持旧版浏览器,可能需要使用XMLHttpRequest。
评论已关闭