Access function object and use it anywhere

1

I made a request from a json file and passed it to a function.

$.post('principal/json',minhaCallBack,'json'); //Requisição

function minhaCallBack(returnhtml){   //função

var json = returnhtml;

console.log('json', json);
return json;

};

In my console, I perfectly see the object I want:

    Object {geral: "", home: Array[11], header: "", menu: Array[7], cadastro: Array[10]…}
            10+:Array[3]
            100+:Array[7]
            aovivo:Array[8]
            artistas:Array[11]
            cadastro:Array[10]
            confirmacao:Array[4]
            contato:Array[13]
            dilema:""
            download:""
            esqueceuModal:Array[5]
            formularioCadastro:Array[32]
            geral:""
            header:""
            home:Array[11]
            menu:Array[7]
            mfy:""
            music_check:""
            noticias:Array[12]
            programacao:""
            promoção:Array[12]
            quemSomos:Array[13]
            recomende:""
            redefinir:Array[7]
Now come on, my goal is to get this object (which is my json file) that is inside the function and use it the way I want, and wherever I want, how can I do something like the example below ?

Example:

<p> json.artistas[0]['atributoQualquerdoObjeto']</p>
    
asked by anonymous 20.06.2016 / 15:33

2 answers

1

Your callback function should perform the necessary action with JSON and not return it.

So if you have a page location where you want to show an attribute, first identify the tag in some way and then fill in accordingly.

Example:

$.post('principal/json', preencheDados, 'json');
function preencheDados(json) {
    $('#campo-geral').text(json.geral);
};

HTML:

<p id="campo-geral"><p>
    
21.06.2016 / 03:49
0

Robson, you can also use a template engine to assemble your HTML, below is an example with Handlebars

I will use the following JSON in the example:

var model = {
    Data: new Date(),
    Pessoas: [
        {"firstName":"Meire","lastName":"Melo","jobTitle":"Direct Marketing Agent","title":"Product Branding Analyst"},
        {"firstName":"Júlio César","lastName":"Reis","jobTitle":"Dynamic Web Designer","title":"Global Usability Designer"},
        {"firstName":"Esther","lastName":"Silva","jobTitle":"Customer Marketing Technician","title":"International Metrics Director"},
        {"firstName":"Kléber","lastName":"Moreira","jobTitle":"Global Paradigm Engineer","title":"Investor Metrics Planner"},
        {"firstName":"Gúbio","lastName":"Macedo","jobTitle":"Dynamic Configuration Assistant","title":"Human Response Orchestrator"},
        {"firstName":"Norberto","lastName":"Albuquerque","jobTitle":"Central Optimization Planner","title":"Customer Optimization Manager"},
        {"firstName":"Dalila","lastName":"Oliveira","jobTitle":"Dynamic Data Producer","title":"Product Accountability Manager"},
        {"firstName":"Yuri","lastName":"Reis","jobTitle":"Dynamic Functionality Specialist","title":"Dynamic Usability Technician"},
        {"firstName":"Vicente","lastName":"Pereira","jobTitle":"Senior Optimization Strategist","title":"Central Accountability Producer"},
        {"firstName":"Elísio","lastName":"Saraiva","jobTitle":"Internal Division Producer","title":"Dynamic Interactions Engineer"},
        {"firstName":"Lorraine","lastName":"Braga","jobTitle":"Corporate Security Strategist","title":"Corporate Creative Coordinator"},
        {"firstName":"Guilherme","lastName":"Albuquerque","jobTitle":"Internal Accountability Agent","title":"Senior Research Developer"},
        {"firstName":"Rafaela","lastName":"Melo","jobTitle":"Corporate Paradigm Orchestrator","title":"National Division Manager"},
        {"firstName":"Heitor","lastName":"Reis","jobTitle":"Dynamic Integration Assistant","title":"Chief Brand Engineer"},
        {"firstName":"Sílvia","lastName":"Martins","jobTitle":"Principal Division Engineer","title":"Global Configuration Analyst"},
        {"firstName":"Alessandro","lastName":"Carvalho","jobTitle":"Direct Security Planner","title":"Direct Tactics Architect"},
        {"firstName":"Roberta","lastName":"Macedo","jobTitle":"Lead Metrics Orchestrator","title":"Dynamic Mobility Analyst"},
        {"firstName":"Silas","lastName":"Moreira","jobTitle":"Direct Communications Manager","title":"Regional Functionality Planner"},
        {"firstName":"Marli","lastName":"Moraes","jobTitle":"Lead Accounts Technician","title":"Senior Assurance Consultant"},
        {"firstName":"Meire","lastName":"Braga","jobTitle":"District Interactions Manager","title":"Forward Web Officer"}
    ]
};

The template will be as follows:

<div>
    <label>
        Data:
        <input type="text" value="{{formatDate Data}}" />
    </label>
</div>
<div>
    <table>
        <thead>
            <tr>
                <th>Nome</th>
                <th>Sobrenome</th>
                <th>Profissão</th>
                <th>Titulo</th>
            </tr>
        </thead>
        <tbody>
        {{#each Pessoas}}
            <tr>
                <td>{{firstName}}</td>
                <td>{{lastName}}</td>
                <td>{{jobTitle}}</td>
                <td>{{title}}</td>
            </tr>
        {{/each}}
        </tbody>
    </table>
</div>

the markup above you can put in and a <script type="text/x-handlebars-template"></script> tag or a <template></template> tag

To build the template and the final html, you can do this:

var source   = document.getElementById("id do templete").innerHTML;
var template = Handlebars.compile(source);
var html     = template(model);

Now the complete example:

Handlebars.registerHelper('formatDate', function(data, options) {
  return data.toISOString().substring(0, 10);
});

function createElement (html) {
  var template = document.createElement("template");
  template.innerHTML = html;
  return document.importNode(template.content, true);
}

var model = {
    Data: new Date(),
    Pessoas: [
        {"firstName":"Meire","lastName":"Melo","jobTitle":"Direct Marketing Agent","title":"Product Branding Analyst"},
        {"firstName":"Júlio César","lastName":"Reis","jobTitle":"Dynamic Web Designer","title":"Global Usability Designer"},
        {"firstName":"Esther","lastName":"Silva","jobTitle":"Customer Marketing Technician","title":"International Metrics Director"},
        {"firstName":"Kléber","lastName":"Moreira","jobTitle":"Global Paradigm Engineer","title":"Investor Metrics Planner"},
        {"firstName":"Gúbio","lastName":"Macedo","jobTitle":"Dynamic Configuration Assistant","title":"Human Response Orchestrator"},
        {"firstName":"Norberto","lastName":"Albuquerque","jobTitle":"Central Optimization Planner","title":"Customer Optimization Manager"},
        {"firstName":"Dalila","lastName":"Oliveira","jobTitle":"Dynamic Data Producer","title":"Product Accountability Manager"},
        {"firstName":"Yuri","lastName":"Reis","jobTitle":"Dynamic Functionality Specialist","title":"Dynamic Usability Technician"},
        {"firstName":"Vicente","lastName":"Pereira","jobTitle":"Senior Optimization Strategist","title":"Central Accountability Producer"},
        {"firstName":"Elísio","lastName":"Saraiva","jobTitle":"Internal Division Producer","title":"Dynamic Interactions Engineer"},
        {"firstName":"Lorraine","lastName":"Braga","jobTitle":"Corporate Security Strategist","title":"Corporate Creative Coordinator"},
        {"firstName":"Guilherme","lastName":"Albuquerque","jobTitle":"Internal Accountability Agent","title":"Senior Research Developer"},
        {"firstName":"Rafaela","lastName":"Melo","jobTitle":"Corporate Paradigm Orchestrator","title":"National Division Manager"},
        {"firstName":"Heitor","lastName":"Reis","jobTitle":"Dynamic Integration Assistant","title":"Chief Brand Engineer"},
        {"firstName":"Sílvia","lastName":"Martins","jobTitle":"Principal Division Engineer","title":"Global Configuration Analyst"},
        {"firstName":"Alessandro","lastName":"Carvalho","jobTitle":"Direct Security Planner","title":"Direct Tactics Architect"},
        {"firstName":"Roberta","lastName":"Macedo","jobTitle":"Lead Metrics Orchestrator","title":"Dynamic Mobility Analyst"},
        {"firstName":"Silas","lastName":"Moreira","jobTitle":"Direct Communications Manager","title":"Regional Functionality Planner"},
        {"firstName":"Marli","lastName":"Moraes","jobTitle":"Lead Accounts Technician","title":"Senior Assurance Consultant"},
        {"firstName":"Meire","lastName":"Braga","jobTitle":"District Interactions Manager","title":"Forward Web Officer"}
    ]
};

var source   = document.getElementById("tmpl").innerHTML;
var template = Handlebars.compile(source);
var html     = template(model); 
var elem     = createElement(html);
document.body.appendChild(elem);
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.js"></script><scriptid="tmpl" type="text/x-handlebars-template">
  <div>
    <label>
      Data:
      <input type="date" value="{{formatDate Data}}" />
    </label>
  </div>
  <div>
    <table>
      <thead>
        <tr>
          <th>Nome</th>
          <th>Sobrenome</th>
          <th>Profissão</th>
          <th>Titulo</th>
        </tr>
      </thead>
      <tbody>
        {{#each Pessoas}}
        <tr>
          <td>{{firstName}}</td>
          <td>{{lastName}}</td>
          <td>{{jobTitle}}</td>
          <td>{{title}}</td>
        </tr>
        {{/each}}
      </tbody>
    </table>
  </div>
</script>
    
21.06.2016 / 15:06