Files
ClassContent/历届学生/front-end-team-10/项目练习/学生项目/韩孟雪/2023-3-4/ajax_test.html
2024-09-27 02:06:13 +08:00

64 lines
1.6 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 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>ajax_test</title>
</head>
<body>
<ul>
<li>
<div></div>
<img src="" alt="">
</li>
</ul>
</body>
<script>
var xhr = new XMLHttpRequest();
//通过GET请求
xhr.open("GET", "http://127.0.0.1:3000/api/json/index")
//发送请求
xhr.send()
xhr.onreadystatechange = () => {
//响应成功4,请求成功200
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//data 字符串类型的对象或数组传
var data = JSON.parse(xhr.response)//从response中取数据
//数据存放在result 中
console.log(data.result.list);
//console.log(data.status);
//console.log(xhr.response);
data.result.list.forEach((v => {
document.querySelector("ul").innerHTML += `
<li>
<div class="title">${v.title}</div>
<img src="${v.img_src}" alt="">
</li>
`
}))
}
} else {
alert("当前网络不佳,请稍后重试!")
}
}
var a = {
id: 1,
name: "张三",
age: "18"
}
//转换成字符串
var c = JSON.stringify(a)
console.log(c);
// console.log(typeof a);//object
// console.log(a.name);
</script>
</html>