AJAX(Asynchronous JavaScript and XML)是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。在原生JavaScript中,可以通过XMLHttpRequest对象来实现AJAX请求。以下是关于原生JS中AJAX的参数及其相关概念:
open(method, url, async)
xhr.open('GET', 'https://example.com/api/data', true);
send(data)
xhr.send(null); // GET请求
xhr.send(JSON.stringify({key: 'value'})); // POST请求
setRequestHeader(header, value)
xhr.setRequestHeader('Content-Type', 'application/json');
onreadystatechange
readyState
属性获取当前状态。xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
// 服务器端设置CORS头
Access-Control-Allow-Origin: *
xhr.timeout = 5000; // 设置超时时间为5秒
xhr.ontimeout = function() {
console.log('请求超时');
};
if (xhr.status === 404) {
console.log('资源未找到');
} else if (xhr.status === 500) {
console.log('服务器内部错误');
}
通过理解和正确使用这些参数和方法,可以有效利用AJAX提升Web应用的性能和用户体验。
领取专属 10元无门槛券
手把手带您无忧上云