print json on pure javascript screen

Asked

Viewed 3,652 times

1

I have this following json structure:

"[{
"nome":["fulano 1","fulano 2","fulano 3","fulano 4"],
"site":["sitefulano1.html","sitefulano2.html.html","sitefulano3.html","sitefulano2.html"]}]"

I manage it this way with php and mysql Pdo:

<?php
$valorV1 = count($v1);

for($col = 0; $col <= $valorV1-1; $col++) {
$autores['nome'][] = $v1[$col]['value'];
$autores['site'][] = $v2[$col]['site'];
}
  echo json_encode([$autores]);
?>

The problem I want to put the json data on the screen and can’t, someone knows how to fix?

I tried some examples didn’t work:

function trataResposta(requisicaoAjax) {
    if(requisicaoAjax.readyState == 4) {
      if(requisicaoAjax.status == 200 || requisicaoAjax.status == 304) {    
            var dados = requisicaoAjax.responseText;
            alert(dados);

//tentei = 

var jsonObj = JSON.parse(dados);
  for (var i=0; i < jsonObj.length; i++){   
      alert(jsonObj[i]);   
  }       

    for (var i=0; i < autores.dados.length; i++) { //vai passar por todos os objetos dentro do array
     document.getElementById('insere_aqui').innerHTML = dados[i]["nome"];
     document.getElementById('insere_aqui').innerHTML = dados[i]["site"];
    }


      }
    }
}

When I tried this way the example works but with my json coming from the bank does nothing!

var Ex01 = {"indice":"valor","nome" : "Silas Stoffel"}

  for (var index in dados ) {   
      alert(index + ': ' + Ex01[index]);   
  }       

Another question is how do I do it, in case you want to put a name on the json like that? In the book case, how do I do this with php and mysql?

{ "livro" :{
    "titulo" : "Construindo sites com CSS e (X)HTML",
    "autor" : "Maurício",
    "site" : "http://livrocss.com.br"
    }
} 

was written Object on the console when I opened the arrow appeared the data inside

Object
nome
:
"fulano1"
site
:
"sitefulano1.html"
__proto__
:
Object
1
:
Object
nome
:
"fulano2"
site
:
"sitefulano2.html"
__proto__
:
Object
2
:
Object
nome
:
"fulano3"
site
:
"sitefulano3.html"
__proto__
:
Object
3
:
Object
nome
:
"fulano4"
site
  • 1

    your second question does not work because you are trying to paste a structure into Alert that only accepts simple string. If you change the function Alert to console.log I believe it works.

  • I got was not sure if the right name is this in the Dice or object level console.log(dados[0].nome); console.log(dados[1].nome); console.log(dados[2].nome); Ae appeared the data

  • Was any of the answer helpful? Don’t forget to choose one and mark it so it can be used if someone has a similar question!

3 answers

1

Going for the simplest:

function imprimirJSON(json) {
  console.log(JSON.stringify(json));
}

And the call you make for:

imprimirJSON(meuJSON);

JSON.stringify()

The method JSON.stringify() converts values into javascript for a String JSON. These values can be replaced by specifying the function replacer, or including only specific properties, when the array of replacer for specified.

1

You are generating json in the wrong way. Try it like this:

array $autores(
    'nome' => $v1[$col]['value'],
    'site' => $v2[$col]['site']
)

echo json_encode([$autores]);

If it doesn’t work with '=>' try with ':' I can’t remember which of the two is correct.

I don’t understand what you want to do on the second question.

  • The second doubt follows: { "book" :{ "title" : "Building sites with CSS and (X)HTML", "author" : "Mauritius", "site" : "http://livrocss.com.br" } } the name of this json object is called book. The doubt would be, how do I put a name like that in my with php? how do you build this structure? the name could be clients, employees etc

  • I’ll try to move the vector here

  • @Alexandremartinsmontebelo, what are these keys in $autores, its syntax is incorrect. the correct would be: $autores = array(...) or $autores = array[...]

  • @Ivanferrer truth, corrected in my reply

1

In the same way you do with PHP, you do with javascript, prefer the console to the place of alert(). If you press the F12 key in Chrome, will open his console, in the "console" tab there is the structure output of your data. then to see if there is a way out, just make a console.log(dados);.

Using a jQuery library, you make it easy to create an ajax manual request, which requires many more than this method structure you made, in fact a correct ajax structure would be something similar to this:

function CriaRequest() { 
  try { 
   var request = new XMLHttpRequest();
  } catch (IEAtual) {
    try { 
      var request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(IEAntigo) {
      try {
         var request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch(falha) {
         var request = false;
      }
    }
  }
 if (!request) {
    alert("Seu Navegador não suporta Ajax!");
 } else {
   return request;
}

function getDados() {
  // Declaração de Variáveis
 var nome = document.getElementById("txtnome").value;
 var result = document.getElementById("Resultado");
 var xmlreq = CriaRequest();
 // Exibi a imagem de progresso
 result.innerHTML = '<img src="Progresso1.gif"/>';
   // Iniciar uma requisição GET ou POST
 xmlreq.open("GET", "Contato.php?txtnome=" + nome, true);
   // Atribui uma função para ser executada sempre que houver uma mudança de ado 
     xmlreq.onreadystatechange = function() {
       // Verifica se foi concluído com sucesso e a conexão fechada (readyState=4)
         if (xmlreq.readyState == 4) {
            // Verifica se o arquivo foi encontrado com sucesso
            if (xmlreq.status == 200) { 
                result.innerHTML = xmlreq.responseText; 
            } else {
              result.innerHTML = "Erro: " + xmlreq.statusText; 
            } 
         }
     };
xmlreq.send(null);
}

Now, we’ll save lines using jQuery:

1) Include the library if you want to use CDN:

<script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>

2) use the request method: $.ajax(), create a method to read your post:

function enviarDados(dados)
{
//a estrutura de dados enviados pode ser um json, exemplo: {"chave1":"valor1", "chave2":"valor2"};
    $.ajax({
        type: 'POST',
        url: URL,
        async: true,
        cache: false,
        dataType : "json",
        data: dados,
        success: function(jsonData)
        {
          //jsonData é o objeto de retorno do método (já em json)

           //para ler seu dados, você tanto pode converter tudo em uma string:
           document.body.innerHTML = JSON.stringify(jsonData, false,'    ');
           //como pode decidir fazer um loop no objeto:

           for (var i in jsonData) {
                for (var y in jsonData[i].nome) {
                    //saída é fulano1, fulano2 ...
                    console.log(jsonData[i].nome[y]);
                }
           }

        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        {
          alert('Erro: '+errorThrown+"\nna requisição: "+XMLHttpRequest+"\nStatus: "+textStatus);

        }
    });

$(funcion() {
  enviarDados('{chave1:valor1}');
});

Here is another example, working with JSON.

  • 1

    The problem that is a store in Gento and already have libraries jquery, I’m afraid of conflict so I wanted to use the pure js.

  • if you already have a jquery library, then you will not conflict. The conflict only occurs with scripts from another source such as moontools. And yet, there is the $.noConflict() to solve this. I made an example of ajax request, using pure JS too, is in the answer, just change the input/output of data the way you want.

Browser other questions tagged

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