📅  最后修改于: 2023-12-03 14:59:12.648000             🧑  作者: Mango
AJAX 英文全称是 Asynchronous JavaScript and XML,即异步 JavaScript 和 XML。其核心是通过浏览器的 XMLHttpRequest 对象来向服务器发送异步请求,从而实现无需刷新页面即可更新数据的效果。
使用 AJAX 可以带来以下好处:
var xhr = new XMLHttpRequest();
xhr.open('GET', '/data', true); // true 表示开启异步请求
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
}
以上代码块中,readyState
表示当前请求状态,通常会有以下 5 种取值:
status
表示服务器响应的状态码,通常会有以下几种:
xhr.open('POST', '/data', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('name=value');
setRequestHeader
方法可以设置请求头,一般用于 POST 请求时设置请求参数的格式,如 Content-type: application/x-www-form-urlencoded
表示参数的格式为"键值对"。
send
方法中的参数表示请求主体,用于传递参数。
xhr.open('POST', '/data', true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.send(JSON.stringify({name: 'value'}));
当需要发送 JSON 数据时,需要将请求头设置为 Content-type: application/json
,并将数据通过 JSON.stringify
方法将其转换为 JSON 格式的字符串。
通过 AJAX 发布请求,我们可以实现异步请求,提高用户体验和页面性能。发送异步请求主要是通过 XMLHttpRequest 对象,发送 POST 请求时需要设置请求头,发送 JSON 数据时需要通过 JSON.stringify
方法进行转换。