Php 如何结束json数据数组并回显另一个值?
我使用Php 如何结束json数据数组并回显另一个值?,php,javascript,jquery,Php,Javascript,Jquery,我使用php返回一个数据数组,命令是json\u 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=post
php
返回一个数据数组,命令是json\u 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);
?>
这是一个空间数据库,当我查询信息时,我还想返回一些其他值。例如,如果区域是纽约,则我希望返回一个数据数组以及字符串
newyork
。此时,echo“$('#messages').html('Result returned for New York')”代码>只是附加到信息数组中。是否有一种方法可以从数组中退出,或者我是否需要一个单独的post
函数来获取此信息。而不是echo json\u 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
},
成功:函数(结果){
对于(i=0;i而不是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
},
成功:函数(结果){
对于(i=0;i,假设您使用的是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'
});
像这样,您可以附加或做任何您喜欢的事情。假设您使用的是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'
});
像这样,你可以附加或做任何你喜欢的事情。谢谢@ori!我从你的答案中学到了一些非常有效的新东西。谢谢@ori!我从你的答案中学到了一些非常有效的新东西。