1
自定义请求的示例
2026-08-21 09:42:42
34 次阅读
1 个评论
// 声明一个渲染函数
function updateCard(data) {
// 1. 根据组件id获取组件容器的dom
let dom = document.getElementById('4u2vv9');
// 2. 自定义一个HTML组件
let divhtml = `
<style>
.card-container {
font-size:36px
}
</style>
<div class="card-container">
姓名:${ data && data.data && data.data.name ? data.data.name : '诸葛青'}
</div>
`;
// 3. 将自定义的组件注入 DOM
dom.innerHTML = divhtml;
}
// 声明一个请求地址
const API_URL = 'http://localhost:8080/card'
// 声明一个fetch请求函数
async function getCardData() {
try {
const response = await fetch(API_URL);
// 检查请求是否成功 (status 200-299)
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data)
// 成功获取数据后,更新卡片
updateCard(data);
} catch (error) {
console.error('获取卡片数据失败:', error);
// 这里可以执行降级逻辑,比如显示默认值
}
}
// 初始化执行一次
updateCard();
// 执行请求
getCardData();
async function getData() {
const response = await fetch('http://localhost:8080/card', {
method: 'GET', // 指定请求方法
headers: {
'Content-Type': 'application/json' // 告诉服务器你发的是 JSON
},
body: JSON.stringify({ name: '张三', age: 25 }) // 把对象转成字符串
});
const result = await response.json();
console.log('提交成功:', result);
}
function getDataThen() {
fetch('http://localhost:8080/card')
.then(response => {
// 检查响应状态 (200-299 之间为 ok)
if (!response.ok) {
throw new Error('服务器返回错误: ' + response.status);
}
return response.json();
})
.then(data => {
console.log('成功拿到数据:', data);
})
.catch(err => {
console.error('处理失败:', err.message);
});
}0 赞
0 收藏
评论
- 2026-08-25 09:02:33赞
共 1 条
- 1
页
请登录后回答。没有帐号?注册一个。
