How to send an array to a variable with Json

Asked

Viewed 542 times

2

<!DOCTYPE html >

<html>

<head>
  <link rel="stylesheet" href="demos.css" type="text/css" media="screen" />

  <script src="/sistema/jquery/plugins/RGraph/libraries/RGraph.common.core.js"></script>
  <script src="/sistema/jquery/plugins/RGraph/libraries/RGraph.common.dynamic.js"></script>
  <script src="/sistema/jquery/plugins/RGraph/libraries/RGraph.common.tooltips.js"></script>
  <script src="/sistema/jquery/plugins/RGraph/libraries/RGraph.line.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  <script type="text/javascript" src="http://www.google.com/jsapi"></script>
  <script type="text/javascript">
    google.load("jquery", "1.3.2", {
      uncompressed: true
    });
  </script>
  <script type="text/javascript" src="json.class.js"></script>

  <!--[if lt IE 9]><script src="../excanvas/excanvas.js"></script><![endif]-->

  <p style="margin-left:50em;">
    <title>Cotação USD x BRL</title>
  </p>

  <meta name="robots" content="noindex,nofollow" />
  <meta name="Descrição" content="Cotação do Dolar de Acordo com o Real" />

</head>

<body>

  <h2></h2>

  <canvas id="cvs" width="900" height="300">[No canvas support]</canvas>

  <script>
    $(document).ready(function() {

      var data = [JSON.parse(document.getElementById('valor').value);];
      var tooltips = [];


      //[2.59,2.60,2.40,2.67,1.78];

      // Create the tooltips
      for (var i = 0; i < data.length; i += 1) {
        tooltips[i] = '1 USD = ' + String(data[i] + ' Reais')
      }

      var line = new RGraph.Line({
        id: 'cvs',
        data: data,
        options: {
          tooltips: {
            self: tooltips,
            highlight: false
          },
          colors: ['#058DC7'],
          filled: true,
          fillstyle: 'rgba(229,243,249,0.5)',
          tickmarks: 'filledcircle',
          background: {
            grid: {
              vlines: false,
              border: false,
              autofit: {
                numhlines: 10
              }
            }
          },
          shadow: false,
          linewidth: 3,
          gutter: {
            left: 50,
            right: 20
          },
          numxticks: 0,
          ylabels: {
            count: 5
          },
          axis: {
            color: '#aaa'
          },
          text: {
            color: '#aaa'
          },
          labels: ['21/01', '22/01', '23/01', '24/01', '25/01']
        }
      })

      RGraph.ISOLD ? line.draw() : line.trace2();

    })
  </script>

  <div id="valor"></div>
  <div id="label"></div>

</body>

</html>

At the end of the code this sending the result to a div called "value" wanted to send directly to a variable in javascript has as ?

// Classe para chamar o Json.
function json() {
  var qtd;
  var retorno;

  // Resgatar valores.
  json.prototype.resgatarValores = function() {
    $('#resultado').html('Carregando dados...');

    // Estrutura de resultado.
    $.getJSON('/webpro/webadm/lncidjson', function(data) {
      this.qtd = data.usuarios.length - 1;
      this.valore = '';
      this.label = '';

      for (i = 0; i < this.qtd; i++) {
        if (i == (this.qtd - 1)) {
          this.valore += data.usuarios[i].valor;
          this.label += data.usuarios[i].descr;
        } else {
          this.valore += data.usuarios[i].valor + ',';
          this.label += data.usuarios[i].descr + ',';
        }
      }

      $('#valor').html(this.valore);
      $('#label').html(this.label);
    });

  }

}

// Objeto.
var obj = new json();
obj.resgatarValores();

1 answer

1

If you want to get off that call AJAX I mean that you pass a callback function. So you can run the same asynchronously as is the nature of ajax / $.getJSON.

Something of the style:

obj.resgatarValores(function(data, labels){
   // aqui podes fazer algo com a variável (tipo array) "data" e "lavels" que terá o valor de "valore" e "label" dentro da chamada ajax.
   // Esta callback é corrida quando o ajax/getJSON tiver recebido resposta do servidor
});

and in the other part of the code something like:

json.prototype.resgatarValores = function (callback) { // aqui dás a callback como argumento
    $('#resultado').html('Carregando dados...');

    // Estrutura de resultado.
    $.getJSON('/webpro/webadm/lncidjson', function (data) {
        var valore = data.usuarios.map(function (u) {
            return u.valor;
        });
        var label = data.usuarios.map(function (u) {
            return u.descr;
        });
        // aqui usas a callback, passando o "valor" quando ele tiver chegado do servidor
        callback(valore, label); 

    });
}

Notice you can have this json.prototype.resgatarValores = function (callback) { outside the constructor function. Or simply do this.resgatarValores = function (callback) {

  • Sergio, more with command to the variable instead of the div ?

  • If you follow my suggestion he’ll send this.valore into the variable valor of callback. Get the idea? If you don’t explain to me what is the next step where you want to use that JSON value that I add explanation to the answer.

  • If I edited the above-what code he is doing is the following he sends to the correct "value" div, when I told him to take from the div "var data = [JSON.parse(Document.getElementById('value').value);];" it does not bring anything you can tell me why why you can tell me why ?

  • @nardo_warlock you are taking a few extra steps, unnecessary (by the way they hinder!). It makes no sense to convert into string and then back to array... Run the chart code inside that callback and use the code I just changed.

  • a doubt you put up there about the "obj.reschedValores(Function(data, Labels){" I changed the code as recommended by you, but here for me still did not appear the values of the graph.

  • @nardo_warlock has a link to the page? or can you make a jsFiddle? otherwise it is difficult to reproduce its problem and since you cannot take the last step alone it is difficult to know how to help...

  • How can I show this callback on html page ?

Show 2 more comments

Browser other questions tagged

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