Problem with JS/Jquery/JSON/AJAX

Asked

Viewed 218 times

1

I’m having some problems with JSON in my application and wanted to see if you can help me, please.

The situation is as follows:

I have a method in my controller that searches some items:

@RequestMapping(value = "/buscaTodosCardapios", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public String buscaTodosCardapios(Usuario usuario, Model model){
    JSONObject retorno = new JSONObject();
    try{        
        retorno.put("data", cardapioRepository.findBySubmenuIsNull());
    }catch (Exception ex){
        retorno.put("situacao", "ERRO");
        retorno.put("mensagem", "Falha ao iniciar produção!");
    }
    return retorno.toString();
}

A JS file that picks up these items:

function buscaTodosCardapios(){
$.ajax({
    url: "buscaTodosCardapios",
    type: 'GET',
    dataType: 'json',
    cache: false,
    success: updateCardapios
});
}

function updateCardapios(data){
    console.log(data);
    console.log(data.cardapioId);
}

Everything returns OK: inserir a descrição da imagem aqui

Only, as you can see, the second console.log, it returns nothing and I can’t get it to pick up any element from within the date. Can someone help me with that?

-EDIT- Solution for those who need it:

console.log(data.data[0].cardapioId);
  • Check an answer if you found the solution, for more information see [tour]

3 answers

2


you are returning an array.

Use This

console.log(data.data[0].cardapioId);
  • Returns the following error: Uncaught Typeerror: Cannot read Property 'cardapioId' of Undefined

  • Exactly I changed now for this try like this

  • A little before opening here, I ended up testing this way and it worked, anyway, thank you!

  • When an answer contains the solution of your question, accept it as an answer and do not edit your question for it

0

As you are bringing an array of objects, to gain access, it will have to be:

console.log(data.data[0].atributo);
  • I have tried this and it returns me the following error: Uncaught Typeerror: Cannot read Property 'cardapioId' of Undefined

  • from a.log console(data[0]) and show what appears.

  • Everything worked out here, already edited the post. Thanks for trying to help!

0

Hello, when you use the @Requestmapping annotation to produce={"application/json"} you don’t need to write it down with @Respondebody. You also don’t need the return to be string type, you can directly return the object and Spring will transform it into json format.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.