【发布时间】:2021-10-10 20:16:24
【问题描述】:
例如,这里是远程 URL 上 JSON 的内容:
{ "title": "The title", "description": "The description" }
你能帮忙吗:
- 我想从远程 url 获取 json 数据(异步任务)。
- 返回值时,我想在DIV中显示标题(json)。
下面的函数在我的 DIV 中显示“[object Promise]”。
async buildWidget() {
var id = "whatever"
let data = await fetch('getItem.php?id=' + id + '&callback=getJSONP');
var json = data.json();
return json.title;
}
请不要使用 JQuery。
谢谢
【问题讨论】:
-
json是一种异步方法。在从中读取字段之前,您还需要await它。 -
1.在
data.json()之前放置一个await关键字。 2.调用buildWidget函数为:buildWidget().then(title => { /* show title in div */}).catch(err => { /* handle error*/})。 -
我明白了,主要问题是我如何调用该函数。谢谢
-
如果你调用
buildWidget()的上下文也是异步的,那么你可以简单地使用await buildWidget()
标签: javascript async-await fetch