Browse JSON in JavaScript

2

The following scenario is presented to me, I have in my HTML a <textarea> in which the user will enter a query, as if it were the command line, example, I can enter:

  

SELECT * FROM users;

     

SELECT * FROM countries;

     

SELECT email, nickname, range FROM users WHERE userID = 1;

With a request AJAX I send the query that I want, it returns me a JSON that contains the records of the query.

For example, for the first query above, the generated JSON is as follows:

link

And for the second query is the following:

link

How can I navigate through these JSONs? Obtaining the headers and their registers, in order to generate a table HTML with the data obtained.

This is what I have in my file JS I get the records and create the tables, but without their corresponding headers.

$(document).ready(function() {
	$('#realizarQuery').click(function(event) {
		event.preventDefault();
		var valorTextArea = $('#valorTextArea').val();
		$.ajax({
			url: 'realizarQuery.php',
			type: 'POST',
			dataType: 'JSON',
			data: {valorTextArea},
		})
		.done(function(data) {
			console.log("success");
			console.log(data);
			console.log(typeof data);
			$.each(data, function(index, val) {
			 if (val == '¡Escribe tu query!') {
			 	$('#texto').html('¡ESCRIBE TU QUERY!').css('font-size', '20px').css('color', '#D50000');
			 	$("#registrosIntermedios").html('').hide();
			 }else if( val == '¡Verifique su sentencia SQL!'){
			 	$('#texto').html('¡VERIFIQUE SU SENTENCIA SQL!').css('font-size', '20px').css('color', '#D50000');
			 	$("#registrosIntermedios").html('').hide();
			 }else{
			 		var tbl_body = "";
					var odd_even = false;
					$.each(data, function() {
    					var tbl_row = "";
    					$.each(this, function(k , v) {
        				tbl_row += "<td>"+v+"</td>";
    				})
    				tbl_body += "<tr class=\""+( odd_even ? "odd" : "even")+"\">"+tbl_row+"</tr>";
    				odd_even = !odd_even;               
					})

					$('#texto').html('LOS REGISTROS QUE CONTIENE SU CONSULTA SON LOS SIGUIENTES').css('font-size', '20px').css('color', '#2E7D32');
					$("#registrosIntermedios").html(tbl_body).show();
					
			 }
		});
		})
		.fail(function() {
			console.log("error");
		})
		.always(function() {
			console.log("complete");
		}, 'json');
		
	});
});

For any contribution, thank you.

    
asked by antonio291093 22.09.2017 в 05:31
source

1 answer

3

In JS, in case the result was successful (your else ), then your first each will go through the rows that were returned.
Use a flag so that in the first row, you can go through the fields of the first record, using the names of the index of the arrangement (that will create your header, with the names of the columns). Then you can put the following row (you go back to that first row of the result), writing now the values ...
In the subsequent ones, you only print the values.
I guess you can use a table for that, put the headers in TH and the data in TD .

I hope you understand my 'pseudo-code', if not, you tell me and I put it more detailed.

You can also check the answers to Convert JSON array to an HTML table in jQuery , although it's in English, you can see that they suggest using jqGrid, and another answer has the code to do it right there, similar to what I described above.

EDITION: I hope with the comments you will be more clear what you are doing. Remove the reference to the "zebra" (alternating classes to decorate the lines). I also added to generate the header of the table.

}else{
    var tbl_body = ""; // Iniciamos con una tabla vacía
    var tbl_row = ""; // para armar cada renglón

    // Encabezado de la tabla:
    // Recorremos el primer renglon, pero usamos los Key.
    // Los key, son los nombres de las columnas.
    $.each(data[0],function(k, v) {
        tbl_row += "<th>"+k+"</th>"; // Usamos TH, porque es el encabezado de la tabla
    }
    // Agregamos el encabezado a la tabla
    tbl_body += "<tr>"+tbl_row+"</tr>";
    // termina bloque nuevo

    // Un ciclo para recorrer los renglones del resultado
    $.each(data, function() {
        tbl_row = ""; // Cada iteracion, vaciamos el renglón

        // Otro ciclo, para recorrer cada campo en el renglon actual
        $.each(this, function(k , v) {
            // Agregamos el campo al renglon.
            tbl_row += "<td>"+v+"</td>";
        })

        // Agregamos el renglón a la tabla
        tbl_body += "<tr>"+tbl_row+"</tr>";
    })

    $('#texto').html('LOS REGISTROS QUE CONTIENE SU CONSULTA SON LOS SIGUIENTES').css('font-size', '20px');
    $("#registrosIntermedios").html(tbl_body).show();
}
    
answered by 22.09.2017 / 07:04
source