2010-10-26 86 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

相关问题