2017-10-18 141 views
0

我想從查詢mysql中獲取數組中的值數組。但是當我檢查控制檯時,我得到了數組中的對象。我將使用我的查詢mysql編寫示例代碼和示例數據和數據。如何在jquery中使用jquery獲取數組中的數組

var locationsSample = [ 
       [-6.175656, 106.812630,'ONSHORE',1,'id1'], 
       [-6.192848, 106.822027,'OFFSHORE',1,'id2'], 
       [-6.164234, 106.328973,'FABRICATION SHOP',1,'id3'], 
       [-0.594009, 100.735315,'SUMATERA',0,'id4'], 
       [5.168138, 97.124416,'SUMATERA ACEH',1,'id5'] 
     ]; 
console.log(locationsSample); 
from console => Array [ Array[5], Array[5], Array[5], Array[5], Array[5] ] this is a true. 

,這是我的PHP代碼:

文件名:jsonarray.php

$qry="SELECT latitude,longitude,project_name,status,id_tbl_project_map FROM tbl_project_map"; 
$res = mysql_query($qry) or die('Query failed: ' . mysql_error()); 
$rows= array(); 
while($data=mysql_fetch_assoc($res)) 
{ 
    $rows[]=$data; 
} 
print json_encode($rows); 

和jQuery調用文件jsonarray.php:

locations = new Array(); 
     $.ajax({ 
      url:"jsonarray.php?id=2", 
      type:"POST", 
      dataType:"json", 
      success:function(retqry){ 
       locations = retqry; 
       console.log(locations); 
from console => Array [ Object, Object, Object, Object, Object ] this is a false. why i'm get a Object not Array[5] from example code in top 
      } 
     }); 

請幫幫忙,謝謝您。

+0

「對象」項目是否有正確的數據?你使用'mysql_fetch_assoc'和你的JSON編碼它們,所以它將把它解釋爲一個Object。 (*注意,您可能希望使用'mysqli'來代替'mysql',並且存在安全漏洞*) –

+0

當我單擊控制檯中的對象時,然後顯示有效數據或數據爲真。 –

+0

好吧,因爲他們是正確的,這裏沒有任何問題。我解釋了爲什麼它是我最後一條評論中的'Object',這是由於PHP中的關聯數組項將被解釋爲JSON中的對象。 –

回答

0

嘗試這種方式來歸檔您的要求,

locations = new Array(); 
$.ajax({ 
    url:"jsonarray.php?id=2", 
    type:"POST", 
    dataType:"json", 
    success:function(retqry){ 
     // locations = retqry; 
     // console.log(locations); 
     var Data = []; 
     $.each(retqry, function(your_key, your_val){ 
      Data.push({ 
       your_key:your_val, 
      }); 
     }); 

     locations = Data; 
    } 
}); 

請注意,這個代碼是沒有經過測試,你可能需要更改代碼,根據自己的需要。希望這對你有用!

問候!

+0

謝謝你,但你的代碼仍然不適合我的情況。 –