<!DOCTYPE html>
<html lang="zh-CN">
<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>fetch</title>
</head>
<body>
<div style="display: inline-grid; gap: 1em">
<button onclick="getHtml(this)">GET-HTML</button>
<button onclick="getJSON(this)">GET-JSON</button>
<button onclick="postJSON(this)">POST-JSON</button>
</div>
<script>
// fetch: 发起http请求,返回 Promise对象,该对象会在请求响应被resolve,返回Response
//
// GET:HTML
const getHtml = async function (btn) {
// 响应对象
const response = await fetch('http://site.io/test1.php', {
method: 'GET',
});
// 处理数据
const data = await response.text();
console.log(data);
// 将html字符串,解析/包装成DOM元素对象
let domparser = new DOMParser();
let doc = domparser.parseFromString(data, 'text/html');
// 将data,解析成了一个完整的html文档对象
console.log(doc);
let ele = doc.body.firstElementChild;
console.log(ele);
// 将ul添加到页面中
if (btn.nextElementSibling.tagName !== 'UL') {
btn.after(ele);
} else {
btn.nextElementSibling.remove();
}
};
// GET:JSON
const getJSON = async function (btn) {
// 响应对象
const response = await fetch('http://site.io/test2.php', {
method: 'GET',
});
// 处理数据
const data = await response.json();
console.log(data);
// 用表格将数据渲染到页面中
const table = document.createElement('table');
table.border = 1;
const caption = table.createCaption();
caption.textContent = '购物车';
const thead = table.createTHead();
thead.innerHTML = '<tr><td>ID</td><td>品名</td><td>单价</td></tr>';
const tbody = table.createTBody();
data.forEach((item) => {
const tr = `
<tr>
<td>${item.id}</td>
<td>${item.name}</td>
<td>${item.price}</td>
</tr>
`;
tbody.innerHTML += tr;
});
// 将ul添加到页面中
if (btn.nextElementSibling.tagName !== 'TABLE') {
btn.after(table);
} else {
btn.nextElementSibling.remove();
}
};
// POST: JSON(参考模板)
const postJSON = async function (btn) {
const response = await fetch('api', {
// 请求类型
method: 'POST',
// 跨域
mode: 'cors',
// 请求头
headers: {
// 内容类型
'Content-Type': 'application/json;charset=utf-8',
},
// 将数据解析为JSON字符串发送
body: JSON.stringify({ id: 4, name: '面包', price: 50 }),
});
//
const data = await response.text();
console.log(data);
};
</script>
</body>
</html>
test1.php
<?php
header("access-control-allow-origin: *");
?>
<ul>
<li><a href="">item1</a></li>
<li><a href="">item2</a></li>
<li><a href="">item3</a></li>
</ul>
test2.php
<?php
// 允许跨域
header("access-control-allow-origin: *");
$data = [
['id'=>1,'name'=>'西瓜', 'price'=>20],
['id'=>2,'name'=>'蛋糕', 'price'=>100],
['id'=>3,'name'=>'大馍', 'price'=>10],
];
echo json_encode($data);