HTML/Html-Javascript/35-Ajax.html
2023-05-01 19:37:40 +08:00

81 lines
1.7 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="btn">按钮</button>
<div id="app">
</div>
<!-- api文档地址
https://api.zzhitong.com/help
-->
<script>
document.querySelector("#btn").onclick = function () {
console.log("点我了");
}
// 表单提交 页面刷新
// 资源重新加载
// 页面信息没了
// Ajax
// 页面资源的局部数据更改
// 页面无状态发送并接收数据
// https://api.zzhitong.com/ip 获取ip地址的api
// Ajax对象
let xhr = new XMLHttpRequest();
console.log(xhr);
// 请求的基本配置
xhr.open("GET", "https://api.zzhitong.com/ip", true);
// 请求配置完成
xhr.send();
// 请求状态
xhr.onreadystatechange = () => {
// xhr.readyState
// 0 未初始化
// 1 服务器以建立连接
// 2 请求已被接受
// 3 请求处理中
// 4 请求完成 响应就绪
// console.log(xhr);
if (xhr.readyState === 4) {
let data = JSON.parse(xhr.response);
console.log(data);
document.querySelector("#app").innerHTML = `
<h1>ip:${data.number_ip.ip.key} 地址: ${data.number_ip.ip.location}</h1>
`
}
};
</script>
</body>
</html>