Retrieving a json and transforming into html

0

I would like to know how to convert this return that I am creating to HTML, it is displaying a string the elemntos html are coming as string in the browser, follow my code below

		      var ul = $('<ul>').appendTo('body');
				var json = { items: httpRequest.response.headDocument};

				var counter = 1;
				$(json.items).each(function(index, item) {

					for (i = 0; i < item.content.length; i++) { 

							if (typeof item.content[i].content.bodyHtml != "undefined") {

    								console.log(item.content[i].content.bodyHtml)
    								console.log(i)

    								 ul.append(


					    				$(document.createElement('li')).text(item.content[i].content.bodyHtml)

					    		);
    						}

    						console.log(item.content)
					}
    
asked by anonymous 16.02.2016 / 12:15

2 answers

1

Bruno, I believe you have recurring doubts on the subject, so let's take an approach.

Note that the JSON you are working on is not unified, some content does not have a Body and some have attachments.

In this case we need to define what is useful and what is not, in the example below I am defining that attachments are optional and content without Body will be ignored.

To build the HTML, instead of doing it in hand, we will use a template, so we will clone this template whenever we need it.

Note that to access the elements of the template, we will do a search by class, always having as its scope the template itself.

Below is the information that will be extracted from httpRequest.response.headDocument :

  • authors.avatar:
  • authors.displayName:
  • authors.profileUrl:
  • content [i] .content.bodyHtml:
  • content [i] .content.createdAt:
  • content [i] .content.attachments [j] .thumbnail_url
  • content [i] .content.attachments [j] .url
  • content [i] .content.attachments [j] .title

then we will reduce to the following structure:

  • authorAvatar
  • authorName
  • authorUrl
  • bodyHtml
  • createdAt
  • attachments []

var tmplConteudo = document.getElementById("tmplConteudo").content;
var tmplAnexo = document.getElementById("tmplAnexo").content;
var url = "https://client-demo-accounts-2.bootstrap.fyre.co/bs3/v3.1/client-demo-accounts-2.fyre.co/379221/MjAxNjAxMjcxMjQyOmRlc2lnbmVyLWFwcC0xNDUzODQwMjgxODk0/init";

var httpRequest = new XMLHttpRequest();
httpRequest.open("GET", url);
httpRequest.responseType = "json";
httpRequest.addEventListener("readystatechange", function () {
  if (httpRequest.readyState == 4){
    if (httpRequest.status == 200){    
      var contents = httpRequest.response.headDocument.content;
      var conteudos = [];
      contents.forEach(function (content, indice) {
        var author = httpRequest.response.headDocument.authors[content.content.authorId];
        if (author && content.content.bodyHtml) {
          var conteudo = {};
          conteudo.authorAvatar = author.avatar;
          conteudo.authorName = author.displayName;
          conteudo.authorUrl = author.profileUrl;
          conteudo.bodyHtml = content.content.bodyHtml;
          conteudo.createdAt = content.content.createdAt;
          conteudo.anexos = [];
          if (content.content.attachments) {
            conteudo.anexos = content.content.attachments.map(function (attachment, indice) {
              var anexo ={}; 
              anexo.thumbnail_url = attachment.thumbnail_url;
              anexo.title = attachment.title;
              anexo.url = attachment.url;
              return anexo;          
            });
          }
          conteudos.push(conteudo);
        }
      });

      conteudos.forEach(function (conteudo, indice) {
        var node = {};
        node.fragment = document.importNode(tmplConteudo, true);
        node.container = node.fragment.querySelector(".container");
        node.avatar = node.container.querySelector(".avatar");
        node.titulo = node.container.querySelector(".titulo");
        node.conteudo = node.container.querySelector(".conteudo");
        node.rodape = node.container.querySelector(".rodape");

        node.avatar.style.backgroundImage = "url('" + conteudo.authorAvatar + "')";
        node.author = node.titulo.querySelector("a");
        node.author.href = conteudo.authorUrl;
        node.author.title = conteudo.authorName;
        node.author.textContent = conteudo.authorName;        
        node.conteudo.innerHTML = conteudo.bodyHtml;

        conteudo.anexos.forEach(function (anexo, indice) {
          var image = {};
          image.fragment = document.importNode(tmplAnexo, true);
          image.link = image.fragment.querySelector(".link");
          image.thumbnail = image.fragment.querySelector(".thumbnail");
          image.link.href = anexo.url;
          image.link.title = anexo.title;
          image.thumbnail.src = anexo.thumbnail_url;
          image.thumbnail.title = anexo.title;
          node.rodape.appendChild(image.fragment);
        });
        document.body.appendChild(node.fragment);
      });
    } else {

    }
  }
});

httpRequest.send();
html, body {
  position: relative;
  width: 100%;
  height: 100%;
  background-color: whitesmoke;
  margin: 0px;
  padding: 0px;
}

.container {
  position: relative;
  background-color: white;
  border-radius: 5px;
  margin: 5px;
  box-shadow: 0px 0px 5px black;
  height: 180px;
}

.container div {
  box-sizing: border-box;
}

.container .avatar {
  position: absolute;
  top: 0px;  
  bottom: 0px;
  left: 0px;
  width: 180px;
  border-right: 1px solid gainsboro;
  
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.container .titulo {
  position: absolute;
  top: 0px;  
  right: 0px;
  left: 180px;
  height: 30px;
  border-bottom: 1px solid gainsboro;
}

.container .conteudo {
  position: absolute;
  top: 30px;  
  right: 0px;
  bottom: 30px;
  left: 180px;
  border-bottom: 1px solid gainsboro;
}

.container .rodape {
  position: absolute;  
  right: 0px;
  bottom: 0px;  
  left: 180px;
  height: 30px;
  border-top: 1px solid gainsboro;
}
<template id="tmplConteudo">
  <div class="container">
    <div class="avatar">

    </div>
    <div class="titulo">
      <a href="" title=""></a>
    </div>
    <div class="conteudo"></div>
    <div class="rodape"></div>
  </div>
</template>

<template id="tmplAnexo">
  <a class="link" href="" title="">
    <img class="thumbnail" src="" title="" />
  </a>
</template>

The above example is not working in the OS, but you can check out JSFIddle

All you will need to do is tailor your template and update the template. in the above example I used a slightly more complex template, it should be simple to change it to use a simple li.

    
16.02.2016 / 13:10
1

That's almost what you already have. The code would look like this:

//Adiciona o elemento "ul" ao elemento "body".
var ul = $('<ul>').appendTo('body');
var json = { items: httpRequest.response.headDocument};

var counter = 1;
$(json.items).each(function(index, item) {
    for (i = 0; i < item.content.length; i++) { 
        if (typeof item.content[i].content.bodyHtml != "undefined") {
            //Cria o elemento "li" e o adiciona ao elemento "ul" que foi instanciado anteriormente.
            $('<li/>')
                .text(item.content[i].content.bodyHtml)
                .appendTo(ul);
        }
    }
}
    
16.02.2016 / 12:32