2012-01-16 187 views
0

我使用php來返回一個數據數組,命令爲json_encode()。我想在發送這個數組後發送一些其他數據。我正在使用jquery庫。我php代碼如下:如何結束json數據數組並回顯另一個值?

<?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 post命令:

$.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

相反的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 
    }, 
+0

感謝@ori!我從你的答案中學到了幾個新的東西,完美運作。 – djq 2012-01-16 18:18:36

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

這樣可以追加或做任何你喜歡的事情..

相關問題