javascript - 使用 javascript 在 fetch 中读取 json
问题描述
下面是在 javascript 中获取的代码:
fetch(url + "?" + o)
.then(response => {
if (response.ok) {
resolve(response.text());
} else {
reject(response.json()); ///issue in read json data how to read json?
}
})
.then(html => {
debugger
document.getElementById('partialresult').innerHTML = html;
})
.catch(err => {
debugger
console.log("Can’t access " + url + " response. Blocked by browser?" + err)
´
document.getElementById('partialresult').innerHTML = err;
});
如果(!response.ok)我需要读取 json 数据,我需要读取 catch 中的 json 数据或任何只需要更新 div 的地方。
返回 Json 格式:
{ success = false, message = "Operation failed." }
如何在 fetch 中读取 json?
编辑:服务器在 html 中返回成功,在 json ..html 中返回失败(错误)工作正常,如果失败案例在 div 中显示,我需要解析 json 数据
解决方案
在您显示的代码中,您尝试使用未在任何地方声明resolve
的reject
标识符(您已显示)。
要解决then
从其回调中返回的承诺,请使用return
返回一个值(或要解决的承诺)或throw
(或被拒绝的承诺)。
在评论中你说:
实际上服务器在 html 中返回成功,在 json 中返回失败(错误)..如果失败案例在 div 中显示,我需要解析 json 数据
为了解决这个问题,我想我会将服务器的错误对象转换为Error
并抛出它;看评论:
fetch(url + "?" + o)
.then(response => {
if (response.ok) {
// Read the HTML that comes with success
return response.text();
} else {
// Read the JSON that comes with the error,
// then use it as an error
return response.json()
.then(serverError => {
throw new Error(serverError.message);
});
}
})
.then(html => {
// Here, you have the HTML result
document.getElementById('partialresult').innerHTML = html;
})
.catch(err => {
// Here you have either a network error or an error
// we caught above and used to create an Error instance
document.getElementById('partialresult').innerHTML = err.message || String(err);
});
推荐阅读
- typescript - 无法通过动态字符串访问“this”对象
- windows - Windows 10,Git Bash - bash: git: command not found
- docker-compose - 使用 Docker 和 Traefik 的有效 HTTPS 证书
- sqlite - 如何用flutter sqlite存储所有数据?
- angularjs - ionic 5 页面转换 url 更改但上一页仍然可见
- vagrant - 带有 vagrant 后处理器的打包程序“找不到 ovf 文件”
- arrays - 如何创建支持轮播行为的数据结构?
- javascript - 如何在在线聊天的 javascript 2D 画布上获得相对鼠标位置,人们可以通过点击移动他们的角色
- java - netty http/2 APNs 客户端(头帧、数据帧)
- firebase - Flutter + Firebase 无密码身份验证不起作用