Access function object and use it anywhere

Asked

Viewed 119 times

1

I made a request for 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 see perfectly 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 take this object(which is my json file) that is inside the function and use it the way I want, and where I want, how can I do something similar to the example below?

Example:

<p> json.artistas[0]['atributoQualquerdoObjeto']</p>
  • I don’t quite understand your question but if you want to use that json after you receive it, you have to use it within your function minhaCallBack or in code called from it.

  • Hello, that’s what I’d like to do, use json, in this case I already have it within my function, what I can’t do is use it. In code from it? would be accessing the function?

2 answers

1

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

So, if you have any place on the page where you want to show an attribute, first identify the tag somehow 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>
  • valeu friend opened my mind, but I have a doubt, and if this "<p id="field-general"><p>" had been created dynamically?...

0

Robson, you can also use a template engine to build 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 tag <script type="text/x-handlebars-template"></script> or a <template></template>

to build the template and the final html, you can do so:

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

Now the full 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>
<script id="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>

Browser other questions tagged

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