JavaScript -- ajax相关知识点的笔记
warning:
这篇文章距离上次修改已过451天,其中的内容可能已经有所变动。
AJAX,即“Asynchronous JavaScript and XML”(异步JavaScript和XML),是指一种创建交互式网页应用的技术。这种用户界面可以不必刷新页面即可更新数据。
- 创建一个新的XMLHttpRequest对象:
var xhr = new XMLHttpRequest();- 打开一个连接到服务器的请求:
xhr.open('GET', 'url', true);- 发送请求:
xhr.send();- 处理服务器响应:
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = xhr.responseText;
// 处理response
}
};示例代码:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};以上代码创建了一个AJAX请求,从https://api.example.com/data获取数据,并在收到数据后将其解析为JSON格式并打印到控制台。
评论已关闭