qfedu-web/www/ajax1.html

41 lines
1.2 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="author" content="flykhan" />
<meta name="keywords" content="c c++ 物联网" />
<title>AJAX的异步请求</title>
</head>
<body>
<div id="ret"></div>
<script>
window.onload = function () {
// 当页面加载完成后,则执行的程序
// 发起异步请求(HTTP)
// 1) 请求方法
// 2) 请求头和请求体的数据怎么放
// 3) 相应的数据的怎么接
let url = "/cgi-bin/data1.cgi";
// 发起get请求为了查询数据从后端获取数据
fetch(url)
.then((resp) => {
if (resp.status == 200) {
if (
resp.headers.get("Content-Type").startsWith("application/json")
) {
return resp.json(); // json 对象
} else {
return resp.text(); // 文本数据
}
}
})
.then((data) => {
console.log(data);
ret.innerText = "id=" + data.id + ", name=" + data.name;
});
};
</script>
</body>
</html>