Lajith
Lajith

Reputation: 1867

Read json in fetch with javascript

Below is code for fetch in 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;
 });

I need to read json if (!response.ok) i need to read the json data in catch or any where just div need to updated..

Return Json format:

{ success = false, message = "Operation failed." }

How to read json in fetch?

EDIT : server return succees in html and failure( error) in json ..html working fine and i need parse json data if failure case show in div

Upvotes: 1

Views: 256

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074305

In the code you've shown, you're trying to use resolve and reject identifiers that haven't been declared anywhere (that you've shown).

To settle the promise returned by then from within its callback, use return to return a value (or a promise to resolve to) or throw (or a rejected promise).

In a comment you've said:

Actually server return succees in html and failure( error) in json ..i need parse json data if failure case show in div

To handle that, I think I'd convert the server's error object into an Error and throw it; see comments:

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

Upvotes: 1

Related Questions