首页 > 解决方案 > 使用 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 数据

标签: javascript

解决方案


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

要解决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);
    });

推荐阅读