传递JSON数组中的每个对象进行查询

时间:2014-12-30 21:06:13

标签: jquery arrays json

我正在运行如下所示的查询:

var ready_data= $.getJSON('URL HERE', function (data) {
var id_value= data.rows.map(function (row) {
  return [row[1]+","+ row[2]];
});

var id_value在我的控制台日志中返回,如下所示:

Array[1]]0: Array[1]0: "34.154321,-118.349126"length: 1__proto__: Array[0]1: Array[1]2: Array[1]3....

为了清楚起见,我只是展示了部分内容。但基本上,我从我的getJSON(他们的地图坐标)中找到了与我的查询条件匹配的每个项目的数组。

我想要做的是将每个数组(一次一个)放入查询中并获取结果。现在,我正在使用它:

 $.each(id_value,function(data) {

  var key='MY API KEY'
          var table ='TABLE NUMBER'
           var sql = "SELECT COUNT() from " + table +
              " WHERE ST_INTERSECTS(coordinates,CIRCLE(LATLNG("+id_value+"), 16093 ))";
              url = "https://www.googleapis.com/fusiontables/v1/query?key=" +     encodeURIComponent(key) + "&sql=" + encodeURIComponent(sql) + '&callback=?';
 $.getJSON(url, function (data) {
              $('#info2').append((data.rows ? data.rows[0] : 0) );
          });
});

这不起作用,因为它使用同一查询中的每一对坐标构建一个查询字符串,而不是每个数组一个查询。

我应该如何做到这一点,以便我有一个正常运作的.each循环(或完全不同的东西)?

2 个答案:

答案 0 :(得分:2)

我很确定你的代码应该是这样的:

$.getJSON('URL HERE').done(function (data) {
    $.each(data.rows, function (row, i) {
        var coords = [row[1], row[2]].join(",");

        $.getJSON("https://www.googleapis.com/fusiontables/v1/query?callback=?", {
            key: "MY API KEY",
            sql: "SELECT COUNT() from TABLE NUMBER WHERE ST_INTERSECTS(coordinates, CIRCLE(LATLNG(" + coords + "), 16093))"
        }).done(function (result) {
            console.log("received result " + i, result);
            // deal with the result (remember that they don't arrive in predictable order)
        }).fail(function (jqXHR, textStatus, errorThrown) {
            // don't forget to add error handling
        });
    });
}).fail(function (jqXHR, textStatus, errorThrown) {
     // don't forget to add error handling here, either
});

这会向Google API发送N个请求,一个用于原始数组中的每一行,并为每个N个结果运行回调。

注意如果只是将带有参数的对象传递给jQuery,则不需要处理encodeURIComponent()


编辑:要编排多个异步HTTP请求并在所有完成后运行某个功能,请使用$.when()。我强烈建议您阅读jQuery的Deferred semantics,它们是不可或缺的工具,您应该花时间学习它们的工作原理。

$.getJSON('<QUERY URL HERE>').done(function (data) {
    // create an array of pending Ajax requests
    var xhrRequests = $.map(data.rows, function (row) {
        var latlng = [row[1], row[2]].join(",");
        return $.getJSON("https://www.googleapis.com/fusiontables/v1/query?callback=?", {
            key: "API KEY",
            sql: "SELECT COUNT() from TABLE NUMBER WHERE ST_INTERSECTS(coordinates, CIRCLE(LATLNG(" + latlng + "), 16093))"
        });
    });

    $.when.apply($, xhrRequests).done(function () {
        // this runs after *all* requests have completed successfully
        // arguments contains the results in original request order
        var counts = $.map(arguments, function (xhrResult) {
                // each of the results will be an array [data, status, jqXhr]
                var data = xhrResult[0];
                return data.rows ? data.rows[0] : 0;
            }),
            total = 0;

        // output to the screen, calculate a total, whatever you need
        $.each(counts, function (i, count) {
            total += count;
            $("<div>", {text: count}).appendTo("#info2");
        });

        $("<div>", {text: total}).appendTo("#info2");
    })
    .fail(function (jqXhr, status, textStatus) {
        // this runs as soon as *one* of the requests has failed
        // react to the HTTP error here
        console.log(jqXhr, status, textStatus);
    });
});

我在这里创建了一个更高级,更模块化的实时示例:http://jsfiddle.net/Tomalak/y54tkpz7/1/

答案 1 :(得分:0)

感谢@Tomalak的回复,我能够弄清楚(或者至少是为我工作的东西)。

$.getJSON('<QUERY URL HERE>').done(function (data) {
 var coors = data.rows.map(function (row) {
    return [row[1],row[2]];
});

$.each(coors, function (index,value) {
   var key='API KEY'
          var table ='TABLE NUMBER'
           var sql = "SELECT COUNT() from " + table +
              " WHERE ST_INTERSECTS(coordinates,CIRCLE(LATLNG("+value+"), 16093 ))";
              url = "https://www.googleapis.com/fusiontables/v1/query?key=" + encodeURIComponent(key) + "&sql=" + encodeURIComponent(sql) + '&callback=?';

$.getJSON(url, function (data) {
$('#info2').append(data.rows ? data.rows[0] : 0);
          });

这会将每组坐标的每个计数(10英里内的商店)添加到我的div&#34; info2&#34;。