简体   繁体   中英

How to submit a query request and store it in a variable in javascript?

I'm new to SQL, JSON and Fusion Table. I want to get data from a Fusion Table and store it in a variable in javascript, so that I can append the data in a div element.

This is the javascript I got so far:

    var TopCity;
    TopCity = '{
          "dataSourceUrl": 'http://www.google.com/fusiontables/gvizdata?tq=',
          "query": 
        'SELECT Location FROM 131fgSFd-cumxvMzICckXO-W4CldzfO9J9D--Vw9V ORDER BY Total_Task_Num DESC LIMIT 1',

          }';



    $("#TopCityDiv").append("<div>" + TopCity + "</div>");

Basically, I want to find the city with the top number of completed tasks and display the city name.

I read through the fusion table sql stuff but am still confused: https://developers.google.com/fusiontables/docs/v1/sql-reference

Appreciate all help.

Update: It works!

In order to query my fusion table and not just save it in a table, I need to enable the Fusion Table API and make a public API key.

Working code:

$(document).ready(function() {
    var TopCity;

    $.ajax({
        type: "GET",
        url: "https://www.googleapis.com/fusiontables/v1/query?sql=SELECT+Location+FROM+131fgSFd-cumxvMzICckXO-W4CldzfO9J9D--Vw9V+ORDER+BY+Total_Task_Num+DESC+LIMIT+1&hdrs=false&typed=false&fields=rows&key={API Key}",

        success: function(data) {
            TopCity = data["rows"];
            $("#TopCityDiv").append("<div>" + TopCity + "</div>");
        },
        error: function(xhr, error) {
            console.log('NaN');

        }
    });

});

You should use a callback to get the data. For example, you could use code like below

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {

        var TopCity;

        $.get('https://www.googleapis.com/fusiontables/v1/query?sql=SELECT Location FROM 131fgSFd-cumxvMzICckXO-W4CldzfO9J9D--Vw9V ORDER BY Total_Task_Num DESC LIMIT 1&key={your API key}', function (data, status, xhr) {
            //assign the data to TopCity for future use
            TopCity = data;

            //do something with the data here
            $.("#TopCityDiv").append("<div>" + data + "</div>");
        });
    });
</script>

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