duanquyong8164 2012-01-16 17:48
浏览 62
已采纳

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

I'm using php to return an array of data, with the command json_encode(). I want to also send some other data after I send this array. I'm using the jquery library. My php code is as follows:

<?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);   

?>

This php is responding to a jquery post command:

$.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'
}); 

This is a spatial database, and when I query the information, I also want to return some other values. For example, if the area is New York, I want to return an array of data and also the string New York. At the moment the line echo "$('#messages').html('Result returned for New York')"; just appends to the array of information. Is there a way that I can escape from the array, or do I need to have a separate post function to get this information.

  • 写回答

2条回答 默认 最新

  • duankeng1911 2012-01-16 17:58
    关注

    Instead of echo json_encode($arrayData);, just fetch the meta data and then do:

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

    And then in JQuery:

      success: function(result){  
        for(i=0;i<result.data.length; i++){
          setGeoJson(result.data[i]);
        }
        // do something with result.meta
      }, 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试