如何结束json数据数组,并返回另一个值


How to end an array of json data, and echo another value?

我使用php通过命令json_encode()返回一个数据数组。我还想在发送此数组后发送一些其他数据。我正在使用jquery库。我的php代码如下:

<?php    
////  Query
$sql = "SELECT gtn FROM $table WHERE gid < 10";
//// Open connection 
$con = pg_connect("host=12.12.2.2 port=5434 dbname=spatial_data user=postgres password=****");  
if (!$con){echo 'error connecting'; die; }
//// Run query
$query = pg_query($con, $sql);
$arrayData = array(); // Store results from query in arrays
//// Parse results
while($r = pg_fetch_row($query)) {
    $arrayData[] = $r[0];
}
echo json_encode($arrayData);
//// Return metadata about calculation
//echo "$('#messages').html('Result returned for New York')";
//// close connection
pg_close($con);   
?>

php正在响应jquery后命令:

$.ajax({ 
  type: "POST",
  url: "/php/array_test_v3.php",  
  data:{vertices: pointlist},  
  success: function(arrayData){  
    //console.log(arrayData[0])
    for(i=0;i<arrayData.length; i++){
      setGeoJson(arrayData[i]);
    }
  }, 
  dataType:'json'
}); 

这是一个空间数据库,当我查询信息时,我还想返回一些其他值。例如,如果区域是New York,我希望返回一个数据数组以及字符串New York。此时,行echo "$('#messages').html('Result returned for New York')";只是附加到信息数组中。有没有一种方法可以让我逃离数组,或者我需要一个单独的post函数来获得这些信息。

不使用echo json_encode($arrayData);,只需获取元数据,然后执行:

echo json_encode(array(
    'data' => $arrayData,
    'meta' => $metaData
));

然后在JQuery中:

  success: function(result){  
    for(i=0;i<result.data.length; i++){
      setGeoJson(result.data[i]);
    }
    // do something with result.meta
  }, 

假设您使用的是php。在下面制作这样的阵列

while($r = pg_fetch_row($query)) {
    $arrayData[] = array('gtn'=>$r[0],'someotherkey'=>'someothervalue','anotherkey'=>'anothevalue');
}
echo json_encode($arrayData);

现在在jquery中,您可以进行

$.ajax({ 
        type: "POST",
        url: "/php/array_test_v3.php",  
        data:{vertices: pointlist},  
         success: function(arrayData){  
            $.each(arrayData,function(index,value){
                  setGeoJson(value.gtn);
                  $('#messages').html(value.someotherkey);
               })
        }, 
    dataType:'json'
    }); 

像这样,你可以添加或做任何你喜欢的事情。。