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

时间:2012-01-16 17:48:49

标签: php javascript jquery

我正在使用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。行echo "$('#messages').html('Result returned for New York')";只是附加到信息数组。有没有办法可以从数组中逃脱,或者我是否需要单独的post函数来获取此信息。

2 个答案:

答案 0 :(得分:2)

取代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
  }, 

答案 1 :(得分:1)

假设您使用的是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'
    }); 
像这样,你可以追加或做任何你喜欢的事情。