简体   繁体   中英

How to get data from consumer.query()?

I want to develop a simple webpage using HTML, Javascript and Socrata.

I write this page:

    <body>
    <script src="../lib/soda-js.bundle.js"></script>
    <script>
        var consumer = new soda.Consumer('dati.lombardia.it');
        consumer.query()
            .withDataset('mmyz-duph')
            .limit(100)
            .where({ localita : "Suzzara" })
            .getRows()
                .on('success', function(rows) { console.log(rows); alert('Ok'); })
                .on('error', function(error) { console.error(error); alert('Ci sono problemi'); });



        var righe = consumer.query()
                        .withDataset('mmyz-duph')
                        .limit(100)
                        .where({ localita : "Suzzara" })
                        .getRows();

        /*
            --- Don't work! ---
        for (item in righe) {
            document.write("Email: ");
            document.write(item.email);
            document.write('<br>');
        };
        */

        document.write('<br>');
        document.write('Ho finito di elaborare i dati');
    </script>
</body>

There is a list of chemist's shops in Suzzara (a small Italian city) and I want write email addresses (there are 5 shops). From Firefox's consolle: I see 1 array (5 objects) => OK.

How I can display the email's addresses? Example: Email: pippo@email.com ... ... ... ...

First, JavaScript's "for-in" loop iterates through the keys of an array ( read more here ), not each element of an array.

Second, your JS is performing an AJAX call so your current for loop would be executed before you even got data back from Socrata, so there'd be nothing to loop over. That's why the .on() function is used, so you can execute code once the data is returned.

var consumer = new soda.Consumer('dati.lombardia.it');
consumer.query()
  .withDataset('mmyz-duph')
  .limit(100)
  .where({ localita : "Suzzara" })
  .getRows()
  .on('success', function(rows) {
    // since you're using a for-in loop, this is how it'd work
    for (i in rows) {
      console.log(rows[i]['email']);
    }
  })
  .on('error', function(error) { console.error(error); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM