【搭建你的日记本】在文章正文中添加天气信息

给一个自己的:

<%* 
let ipUrl = 'https://restapi.amap.com/v3/ip';
let weatherUrl = 'https://restapi.amap.com/v3/weather/weatherInfo'
let key = '高德key'

let tencentIpUrl = 'https://apis.map.qq.com/ws/location/v1/ip';
let tencentKey = 'tencent key'

let tencentInfo = eval("(" + 
    await request({url: tencentIpUrl + `?key=${tencentKey}`, method: "GET"})
+ ")").result.ad_info

let adcode = tencentInfo.adcode
let city = tencentInfo.city.slice(0, -1)

let weather = ''
let temperature = ''
await fetch(weatherUrl + `?key=${key}&city=${adcode}&extensions=all`)
.then(res => res.json())
.then((data) => {
	let info = data.forecasts[0]
	weather = (info.casts[0].dayweather === info.casts[0].nightweather) 
              ? info.casts[0].dayweather
              : `${info.casts[0].dayweather}转${info.casts[0].nightweather}`
	temperature = info.casts[0].nighttemp + '~' + info.casts[0].daytemp + '℃'
})
-%>

不同点:

  1. 只显示城市,例如显示:上海、苏州、广州,不显示省,也不显示“市”字
  2. 显示每天的夜间温度与白天温度
  3. 显示每天的夜间天气白天天气,并有条件判断,如果夜间白天天气不一致,则会显示“xx转xx”

效果如下:
image

PixPin_2026-01-08_03-04-37