js请求接口示例
最近在完善自己的网站,记录下前端请求完接口返回数据的模板。
下面分别是一言接口,高德获取位置和获取天气接口的示例。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62// 一言接口
function getHitokoto() {
const url = 'https://v1.hitokoto.cn'
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data)
const hit = data;
<!--这里可以直接将数据返回给id为hitokoto_text的span很方便-->
$('#hitokoto_text').text(hit.hitokoto)-->
$('#hitokoto_auth').text(hit.from_who)
console.log(hit);
})
};
// 替换成你的高德 API 密钥
const amapKey = "xxxxxxxxx";
// 获取用户所在城市并查询天气
function fetchWeather() {
const url = `https://restapi.amap.com/v3/ip?key=${amapKey}`
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data)
if (data.status === '1' ) {
const city = data.adcode;
console.log(city);
getWeather(city);
}
})
.catch(err => {
console.error("请求失败:", err);
});
}
// 使用高德天气查询 API 获取天气信息
function getWeather(city) {
const url = `https://restapi.amap.com/v3/weather/weatherInfo?key=${amapKey}&city=${encodeURIComponent(city)}`;
console.log("请求 URL:", url);
fetch(url)
.then(response => response.json())
.then(data => {
console.log("天气数据:", data);
if (data.status === '1' && data.lives && data.lives.length > 0) {
const weather = data.lives[0];
$('#wea_text').text(weather.city)
$('#tem1').text(weather.weather)
$('#tem2').text(weather.temperature)
$('#tem3').text(weather.winddirection)
$('#tem4').text(weather.windpower)
}
})
.catch(err => {
console.error("请求失败:", err);
});
}
// 初始化
fetchWeather();
getHitokoto();html示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14<!--获取天气-->
<div class="weather">
<span id="wea_text">N/A</span>
<span id="tem1">N/A</span>
<span id="tem2">N/A</span>°C
<span id="tem3">N/A</span>风
<span id="tem4">N/A</span> 级
</div>
<!--一言接口-->
<div class="hitokoto">
<span id="hitokoto_text">这里应该显示一句话</span>
-「<span id="hitokoto_auth">無名</span>」
</div>遇到移动边框会影响其他div的情况时,使用绝对定位
1
2position: absolute; /* 使用绝对定位 */
bottom: 100px; /* 距离底部 50px */毛玻璃特效css
1
2
3
4
5
6
7
8
9
10width: 400px;
padding: 20px;
background: rgba(0, 0, 0, 0.1); /* 半透明白色背景 */
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1); /* 添加阴影 */
backdrop-filter: blur(10px); /* 毛玻璃模糊效果 */
-webkit-backdrop-filter: blur(10px); /* Safari 支持 */
border-radius: 10px; /* 圆角边框 */
border: 1px solid rgba(255, 255, 255, 0.0); /* 更暗的边框线条 */
color: #fff;
text-align: center;
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Tingfeng's Blog!


