Ajax发送请求的方法有多种,常见的有以下几种:
- XMLHttpRequest(XHR):最原始的Ajax方法,通过创建XMLHttpRequest对象来发送和接收数据。
var xhr = new XMLHttpRequest(); xhr.open("GET", "url", true); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send();
- Fetch API:新的浏览器内置API,更加简洁易用,支持Promise,可以替代XMLHttpRequest。
fetch("url") .then(response => response.text()) .then(data => console.log(data)) .catch(error => console.log(error));
- jQuery的Ajax方法:jQuery封装了Ajax功能,通过$.ajax或$.get等方法发送请求。
$.ajax({ url: "url", method: "GET", success: function(data) { console.log(data); }, error: function(error) { console.log(error); } });
- Axios:一个基于Promise的HTTP客户端,支持浏览器和Node.js,可以发送Ajax请求。
axios.get("url") .then(response => console.log(response.data)) .catch(error => console.log(error));
这些方法各有特点,可以根据具体需求选择合适的方法来发送Ajax请求。