2010-10-26 84 views
0

我運行mysql查詢併成功獲取結果。但是,我無法從JavaScript端讀取數組的元素。誰能幫忙?如何將php數組轉換爲javascript數組

//JAVASCRIPT makes a request 

    function profiles(){ 

    $.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "text"); 

    } 


    function fillProfileCombo(res) { 

    alert(res); 

    } 

//dbConn.php takes the request , gets the result and passes via echo as it is shown as follows: 


    //RETURN PROFILE LIST 
    else if (!strcmp($opType, "getProfileList")){ //no param is coming 

    $connect = mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error()); 
    mysql_select_db($db_name) or die(mysql_error()); 

    $profiles = mysql_query(" SELECT DISTINCT profileName FROM `map_locations` "); 
    $row = mysql_fetch_array($profiles); 
    /*while() { 
    echo $row['FirstName'] . " " . $row['LastName']; 
    echo "<br />"; 
    } 
    */ 
    //$data = array(); 
    //$row = mysql_fetch_assoc($profiles) 
    /*while($row = mysql_fetch_assoc($profiles)) 
    { 
    $data[] = $row; 
    }*/ 

    if ($row){ 
    echo $row; 
    } else { 
    echo "ERROR occured"; 
    } 


    } 

//問題:

//當我改變回聲$行; into echo $ row [0];,我看到一個警告框的第一個元素...查詢肯定是工作..

//但是當我改變資源水庫[0],它不會顯示任何東西 - 這是正常的,因爲我不知道如何將php數組轉換爲js數組..

function fillProfileCombo(res) { 
    alert(res[0]); // does not work.. 
} 

我不想用json的方式......我不是很擅長。我不想搞砸了。任何建議和幫助表示讚賞。

+0

爲什麼你不希望使用JSON?這是使用JavaScript代表數據結構的最簡單方法之一 – Phil 2010-10-26 00:14:11

+0

你能給我一個關於這段代碼的例子嗎? – Ozlem 2010-10-26 00:17:22

回答

0
// PHP 
$res = array(); 
while ($row = mysql_fetch_array($profiles)) { 
    $res[] = $row['profileName']; 
} 

header('Content-type: application/json'); 
echo json_encode($res); 

// JavaScript 
$.post('dbConn.php', { opType:"getProfileList" }, function(data) { 
    alert(data.length + " profiles returned"); 
}, "json"); 
+0

感謝Phil,我根據你給我發送的內容糾正了我的代碼。 – Ozlem 2010-10-26 00:46:51

0

感謝Phil..This現在有效。除了一些變化之外,非常相似。我改變了它作爲這樣的:

// PHP

 $data = array(); 
     while($row = mysql_fetch_assoc($profiles)) 
     { 
      $data[] = $row; 
     } 

     if ($data){ 
      echo json_encode($data); 

     } else { 
      echo $data; 
     } 

// JS

function profiles(){ 

     //$.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "json"); 
     $.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "json"); 

    } 


    function fillProfileCombo(data) { 
     alert(data[1].profileName); 

    } 
+0

你應該在嘗試訪問特定索引之前測試JSON數組的長度。 – Phil 2010-10-26 00:50:39

+0

是的我嘗試了你所說的。我嘗試了你發給我的任何東西。但我無法運行它。無論如何,我在你的幫助下糾正了它。非常感謝。 Ozlem。 – Ozlem 2010-10-26 01:00:46

相關問題