我正在使用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
函数来获取此信息。
答案 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'
});
像这样,你可以追加或做任何你喜欢的事情。