开发者

How to cast a php array into javascript array

I run a mysql query and get the results successfully. However, I cannot read the elements of the array from javascript side. Can anyone help??

//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 开发者_JAVA百科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";
   }


  }

//PROBLEM:

//when I change echo $row; into echo $row[0]; , I see the first element in an alert box...query is definitely working..

//however when I change res to res[0], it does not show anything - which is normal because I do not know how to cast php array into js array..

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

I do not want to use json by the way... I am not very good at. I do not want to mess it up. Any suggestion and help is appreciated.


// 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");


Thanks Phil..This works now.. I followed your way by changing sth.. Maybe it was working but I couldnt run it. Very similar except a couple of changes. I changed it as like 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜