HarmonyOS 鸿蒙Next中关于WEB接口返回JSON数据并渲染到页面
HarmonyOS 鸿蒙Next中关于WEB接口返回JSON数据并渲染到页面
import http from '@ohos.net.http';
@Component
struct Index {
@State message: string = 'Hello World'
@State list:Object = {}
aboutToAppear(){
let httphaha = http.createHttp();
httphaha.request("https://www.ssok.cc/zb_system/api.php?mod=post&act=list&id=5",
{
method:http.RequestMethod.GET
}
).then((res) => {
if(res.responseCode ==200){
this.list = JSON.parse(res.result.toString())
console.log(res.result.toString());
for(let c in this.list["data"]["list"]){
console.log(this.list["data"]["list"][c]["ID"])
console.log(this.list["data"]["list"][c]["Title"])
}
}
})
}
build() {
Row() {
Column() {
Row(){
ForEach(this.list["data"]["list"],(item,index)=>{
Text(this.list["data"]["list"][index]["ID"])
})
}
}.width('100%')
}.height('100%')
}
}
更多关于HarmonyOS 鸿蒙Next中关于WEB接口返回JSON数据并渲染到页面的实战教程也可以访问 https://www.itying.com/category-93-b0.html
3 回复
可在 ForEach
外加个 if (this.list.length > 0) { ... }
避开空数组导致的访问报错。
更多关于HarmonyOS 鸿蒙Next中关于WEB接口返回JSON数据并渲染到页面的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
@State list:Object = {}
默认值是空,接口还没等返回数据呢,先执行
ForEach(this.list["data"]["list"],(item,index)=>{
而此时this.list[data]是空的再去[list]必然报错
在HarmonyOS鸿蒙Next中,通过Web组件加载网页并处理JSON数据,可以使用WebController
与JavaScript交互。首先,在Web页面中通过JavaScript请求接口获取JSON数据,然后使用WebController
的postMessage
方法将数据传递到鸿蒙应用。在鸿蒙应用中,通过onMessage
回调接收数据,并使用Component
或List
组件将数据渲染到页面。确保JSON数据格式正确,并通过JSON.parse
解析后动态更新UI。