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条)

报告相同问题?