How to receive JSON data?

Asked

Viewed 1,133 times

0

I want to recover a JSON code for HTML with jQuery. How can I do this? And how can I use CSS with JSON data?

Here is the JSON code.

    {
    "quiz": {
        "sport": {
            "q1": {
                "question": "Which one is correct team name in NBA?",
                "options": [
                    "New York Bulls",
                    "Los Angeles Kings",
                    "Golden State Warriros",
                    "Huston Rocket"
                ],
                "answer": "Huston Rocket"
            }
        },
        "maths": {
            "q1": {
                "question": "5 + 7 = ?",
                "options": [
                    "10",
                    "11",
                    "12",
                    "13"
                ],
                "answer": "12"
            },
            "q2": {
                "question": "12 - 8 = ?",
                "options": [
                    "1",
                    "2",
                    "3",
                    "4"
                ],
                "answer": "4"
            }
        }
    }
}
  • Where is this JSON? You need to receive it via AJAX?

  • Welcome to Stackoverflow! What You Tried?

  • @Andersoncarloswoss It would be nice without AJAX, because I’m having problems with the installation of Winlamp. The code folder is on the desktop, bearing in mind the problems with web server.

  • @Tomásbarcellos I tried using js files to collect json information for html, but none were effective.

  • So you want to read the disk file with Javascript? That’s not possible. You will need to get a web server serving the file and get it with an HTTP request.

  • Take a look at AXIOS https://github.com/axios/axios and Vuejs https://br.vuejs.org/ If you want I can make an example and post as an answer.

  • Which URL and method generates this JSON ?

  • @Tony I’ve never seen about AXIOS, if I may I’d like an example.

  • @Tony This JSON file was not built by me...

  • @Joãovitor gives a read in the Axios documentation. An example of usage would be. axios.get(http://suaurl/).
 then(response => { 
 //Aqui você pega a resposta e trata ela
})
.catch(err => {
 // Aqui trata algum erro na resposta
});

  • You can put here the URL that returns this JSON ?

  • What people meant is that you have to have a source to get this result, whether it’s a string, a URL or a file. Anyway, to use Javascript you need to serve it because by security limitation JS does not allow you to read a file for it.

  • I found an alternative here with some members, I apologize for my nonsense, it’s my first post officially in the stack [which has already become quite obvious].

Show 8 more comments

2 answers

0


To receive JSON you can use AXIOS instead of jQuery with the command axios.get.
To integrate with the HTML and CSS interface you can use Vuejs.

Use this complete example I’ve assembled using HTML, Javascript, Vuejs and AXIOS:

Clicking: View Json using HTML

Create a file Verjson.html and place this content:

<html>
    <head>
        <title>Exemplo JSON</title>

        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <!-- Mobile viewport optimized: h5bp.com/viewport -->
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <meta name="viewport" content="width=device-width" />

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous" />

        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    </head>
    <body>

        <div id="app">
          <h1>{{ message }}</h1><br>

          Versão:<br>
          {{dados.version}}<br>

          Dados:<br>
          <div v-for="detalhe in dados.data">
            Nome:{{detalhe.name}}<br>
            Descricao:{{detalhe.description}}<br>
            <img :src="detalhe.picture" >
            <hr>
          </div>
        </div>

        <script>
        var app = new Vue(
                    {
                        el: '#app',
                        data: 
                        {
                            message: 'Hello Vue!',
                            dados: {}
                        },
                        mounted() 
                        {
                            axios.get("https://exemplos.azurewebsites.net/r7.json.txt").then(response => 
                            { 
                                //Aqui você pega a resposta e trata ela 
                                app.dados = response.data;
                            }).catch(err => 
                            { 
                                // Aqui trata algum erro na resposta 
                                alert(err);
                            });
                            // alert('mounted()');
                        }
                    });
        </script>

    </body>
</html>
  • Thanks, it worked here, now just need to use css apra tidy, but helped a lot. Sorry for the silly questions haha.

  • Thanks! I left the Head link for Boostrap 4, now it’s up to you! http://getbootstrap.com/docs/4.1/layout/overview/

0

Using jQuery, you can use the jQuery.ajax function to receive json and manipulate it.

On the server side, assuming it would be PHP, there would be something like an array with the data, say $data. Mount a URL that returns json_encode($data), passing a header content type: application/json.

header('Content-Type', 'application/json');
return json_encode($data);

In Javascript, I would call:

jQuery.ajax({
   url: 'url do script php q retorna o json(acima)',
   dataType: 'json',
   success: function (response) {
       alert(response[0].name);
   }
});
  • 1

    Another very useful way too, I intend to use too. Thank you, friend

Browser other questions tagged

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