Structure Json in html

4

everyone, Thanks for watching my question, I hope you can help me. is the following ..

I have the following code.

in html

<div id="summary"></div>

In Js I have

   function callurl() {
    $.ajax({
        url: 'https://jsonplaceholder.typicode.com/posts', 
        type: "GET", 
        dataType: "json", 
        success: function (msg) {
            JsonpCallback(msg);
        }, 
        error: function () {
            ErrorFunction();
        }
    });
}

function JsonpCallback(json) {
    document.getElementById('summary').innerHTML = json.title;
}
callurl();

I need to structure the json, in the following way in the html.

With id in each variable. an example would be

<h4>Post ID:<span id="postid"></span></h4>
<h1>Titulo:<span id="titulo"></span></h1>
<h5>Contenido: <span id="contenido"></span></h5>

Someone can help me.

I have some tests on link

UPDATE Thanks to @jorius

I did the update perfectly in link

Now what I'm asking, how can I

If I have json in the following way ..

{
   "orders":[
      {
         "id":12535,
         "order_number":12535,
         "created_at":"2017-03-26T18:10:00Z",
         "updated_at":"2017-03-27T07:25:49Z",
         "completed_at":"2017-03-27T07:25:49Z",
         "status":"processing",
         "currency":"BHD",
         "total":"30.00",
         "subtotal":"30.00",
         "total_line_items_quantity":1,
         "total_tax":"0.00",
         "total_shipping":"0.00",
         "cart_tax":"0.00",
         "shipping_tax":"0.00",
         "total_discount":"0.00",
         "shipping_methods":"",
         "payment_details":{
            "method_id":"credimax",
            "method_title":"Visa \/ Master Card",
            "paid":true
         }
      },      
      {
         "id":33333,
         "order_number":33333,
         "created_at":"2017-03-26T18:10:00Z",
         "updated_at":"2017-03-27T07:25:49Z",
         "completed_at":"2017-03-27T07:25:49Z",
         "status":"processing",
         "currency":"BHD",
         "total":"10.00",
         "subtotal":"10.00",
         "total_line_items_quantity":1,
         "total_tax":"0.00",
         "total_shipping":"0.00",
         "cart_tax":"0.00",
         "shipping_tax":"0.00",
         "total_discount":"0.00",
         "shipping_methods":"",
         "payment_details":{
            "method_id":"credimax",
            "method_title":"Visa \/ Master Card",
            "paid":true
         }
      },
   ]
}

As I can, show

<h5>Order numero: <span id="order_number"></span></h5>
<h5>Fecha: <span id="created_at"></span></h5>

of all ...

    
asked by Juan David 27.03.2017 в 18:13
source

2 answers

4

What happens is that the json that you receive is a array , so you must go through it with a cycle , also, as I see that you are using jquery you can use the selectors and methods of this to make your code simpler, with append we add the information to your div

function callurl() {
  $.ajax({
    url: 'https://jsonplaceholder.typicode.com/posts',
    type: "GET",
    dataType: "json",
    success: function(msg) {
      JsonpCallback(msg);
    },
    error: function() {
      ErrorFunction();
    }
  });
}

function JsonpCallback(json) {
  for (var i = 0; i < json.length; i++) {
    $('#summary').append('<b>Post:</b> ' + json[i].id + '<br />');
    $('#summary').append('<b>Título:</b> ' + json[i].title + '<br />');
    $('#summary').append('<b>Descripción:</b> ' + json[i].body + '<br />');
    $('#summary').append('<hr />');
  }
}

callurl();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="summary"></div>

Regarding the update of your question, it would be basically the same, only that you would access one more level within the object, that is:

var OrdersObject = {
  "orders": [{
      "id": 12535,
      "order_number": 12535,
      "created_at": "2017-03-26T18:10:00Z",
      "updated_at": "2017-03-27T07:25:49Z",
      "completed_at": "2017-03-27T07:25:49Z",
      "status": "processing",
      "currency": "BHD",
      "total": "30.00",
      "subtotal": "30.00",
      "total_line_items_quantity": 1,
      "total_tax": "0.00",
      "total_shipping": "0.00",
      "cart_tax": "0.00",
      "shipping_tax": "0.00",
      "total_discount": "0.00",
      "shipping_methods": "",
      "payment_details": {
        "method_id": "credimax",
        "method_title": "Visa \/ Master Card",
        "paid": true
      }
    },
    {
      "id": 33333,
      "order_number": 33333,
      "created_at": "2017-03-26T18:10:00Z",
      "updated_at": "2017-03-27T07:25:49Z",
      "completed_at": "2017-03-27T07:25:49Z",
      "status": "processing",
      "currency": "BHD",
      "total": "10.00",
      "subtotal": "10.00",
      "total_line_items_quantity": 1,
      "total_tax": "0.00",
      "total_shipping": "0.00",
      "cart_tax": "0.00",
      "shipping_tax": "0.00",
      "total_discount": "0.00",
      "shipping_methods": "",
      "payment_details": {
        "method_id": "credimax",
        "method_title": "Visa \/ Master Card",
        "paid": true
      }
    }
  ]
};

for (var i = 0; i < OrdersObject.orders.length; i++) {
  $('#summary').append('<b>Número de orden: </b>' + OrdersObject.orders[i].order_number + '<br />');
  $('#summary').append('<b>Fecha: </b>' +
    OrdersObject.orders[i].created_at);
  $('#summary').append('<hr />');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="summary"></div>
    
answered by 27.03.2017 / 18:28
source
2

You're doing fine. What you need is to obtain the values of the attributes of the object.

(Besides that each element must have a unique ID) I have modified your code to generate the results like this:

function callurl() {
  $.ajax({
    url: 'https://jsonplaceholder.typicode.com/posts',
    type: "GET",
    dataType: "json",
    success: function(msg) {
      JsonpCallback(msg);
    },
    error: function() {
      ErrorFunction();
    }
  });
}

function JsonpCallback(json) {

  // Variables internas.
  var postId = 0;
  var title = "";
  var body = "";
  var HTML_FINAL = "";

  // Aquí se recorre el objeto JSON devuelto por la llamada.
  for (var i = 0; i < json.length; i++) {

    // Asigno los valores a las variables locales.
    postId = json[i].id;
    title = json[i].title;
    body = json[i].body;

    // Armo el HTML que se colocará en el div "summary":
    HTML_FINAL += '<h4>Post ID:<span id="postid_' + postId + '">' + postId + '</span></h4>' +
      '<h1>Titulo:<span id="titulo_' + i + '">' + title + '</span></h1>' +
      '<h5>Contenido: <span id="contenido' + i + '">' + body + '</span></h5>';
  }

  // Después de salir del ciclo, la variable "HTML_FINAL" tendrá
  // toda la información obtenida. En este paso, se asigna
  // los resultados.
  document.getElementById('summary').innerHTML = HTML_FINAL;
}
callurl();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="summary"></div>

You can access your modified jsfiddle here .

    
answered by 27.03.2017 в 18:26