2014-06-17 193 views
0

我在解碼JSON對象時遇到問題。我使用Ajax調用來調用PHP腳本。 PHP腳本返回一個JSON編碼的對象,我只能讀取第一條記錄。我如何解碼JSON對象?我正在使用JQUERY Mobile。JavaScript陣列的JSON對象?

PHP腳本:

<?php 

    $host = "localhost"; 
    $user = "root"; 
    $pass = "[password]"; 

    $databaseName = "zombieSurvival"; 
    $tableName = "TBLusers"; 

    //Connect to mysql database 

    include 'DB.php'; 
    $con = mysql_connect($host,$user,$pass); 
    $dbs = mysql_select_db($databaseName, $con); 

    // 2) Query database 

    $result = mysql_query("SELECT * FROM $tableName"); 
    $array = mysql_fetch_array($result); 
    echo json_encode($array); 

?> 

,這裏是Ajax調用:

$.ajax({ 
     url: '/PHP/getUserMarkers.php', 
     data: "", 
     dataType: 'json', 
     success: function(data){ 

     //How can I treat 'data' variable to make it a 
     //javascript array? 


     } 
     }); 
+3

即使這是一個'localhost'機器,發佈您的密碼是不可取的。 – JakeGould

+0

你可以在這個副本中看到一個答案:[將JSON對象轉換爲Javascript數組](http://stackoverflow.com/questions/20881213/converting-json-object-into-javascript-array) –

+0

謝謝傑克 - 監督我部分...要看一看由lulian發佈的副本... – user3535074

回答

0

的問題是由PHP腳本返回的JSON對象。調整PHP腳本如下,現在我可以訪問所有返回的行和單個字段名稱。

<?php 

    $host = "localhost"; 
    $user = "root"; 
    $pass = "muertealregueton"; 

    $databaseName = "zombieSurvival"; 
    $tableName = "TBLusers"; 


    include 'DB.php'; 
    $con = mysql_connect($host,$user,$pass); 
    $dbs = mysql_select_db($databaseName, $con); 


    $result = mysql_query("SELECT * FROM $tableName"); 
    $array = array(); 
    while(($row = mysql_fetch_array($result))) { 
     $array[] = $row; 
    } 
    echo json_encode($array); 

?> 

和呼籲的後記錄一個警告的Ajax代碼返回:

$.ajax({ 
     url: '/PHP/getUserMarkers.php', 
     data: "", 
     dataType: 'json', 
     success: function(data){ 


     //now I can access each row and field 
     //like here I access the 3rd field of the 15th record 
     alert(data[15][2]); 



     } 
     });