【问题标题】:Read json in fetch with javascript使用 javascript 在 fetch 中读取 json
【发布时间】:2020-12-19 11:01:21
【问题描述】:

下面是 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 数据

【问题讨论】:

  • "Reutrn Json 格式" 那不是JSON
  • 所以我使用的是 c# ,,, 它有 2 个属性成功和消息
  • resolve(response.text()); ...什么是resolve - 它没有在任何地方定义...也许你的意思是return response.text();?因为这就是 Promises 链的方式

标签: javascript


【解决方案1】:

在您显示的代码中,您尝试使用尚未在任何地方声明的 resolvereject 标识符(您已显示)。

要在其回调中解决then 返回的承诺,请使用return 返回一个值(或要解析的承诺)或throw(或被拒绝的承诺)。

在你说过的评论中:

实际上服务器在 html 中返回成功,在 json 中返回失败(错误)..如果失败案例在 div 中显示,我需要解析 json 数据

为了处理这个问题,我想我会将服务器的错误对象转换为Error 并抛出它;见 cmets:

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);
    });

【讨论】:

  • 非常感谢..实际上服务器在html中返回成功,在json中返回失败(错误)..如果div中显示失败案例,我需要解析json数据
  • @Ajt - 啊!我现在知道了。我已经更新了答案。
  • @Ajt - 重新建议您的编辑:err 对象将是从第一个 then 回调中抛出的 Error,它将具有 message 属性,所以代码是正确的。
猜你喜欢
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
  • 2012-09-30
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多