如何将php数组强制转换为javascript数组
我运行了一个mysql查询并成功地得到了结果。但是,我无法从javascript端读取数组的元素。有人能帮忙吗如何将php数组强制转换为javascript数组,php,javascript,arrays,Php,Javascript,Arrays,我运行了一个mysql查询并成功地得到了结果。但是,我无法从javascript端读取数组的元素。有人能帮忙吗 //JAVASCRIPT makes a request function profiles(){ $.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "text"); } function fillProfileCombo(res) { alert(res);
//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";
}
}
顺便说一下,我不想使用json。。。我不太擅长。我不想把事情搞砸。任何建议和帮助都将不胜感激。谢谢Phil..现在可以了。。我按照你的方式改变了某事。。也许它在工作,但我无法运行它。非常相似,只是有一些变化。我把它改成这样:
// 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");
//PHP
//JS
为什么不想使用JSON呢?这是用JavaScription表示数据结构最简单的方法之一。你能给我一个关于这段代码的例子吗?在尝试访问特定索引之前,你可能应该测试JSON数组的长度。是的,我试过你说的。不管你送我什么我都试过了。但我不能运行它。不管怎样,我在你的帮助下改正了。非常感谢。奥兹勒姆。
// 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");
$data = array();
while($row = mysql_fetch_assoc($profiles))
{
$data[] = $row;
}
if ($data){
echo json_encode($data);
} else {
echo $data;
}
function profiles(){
//$.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "json");
$.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "json");
}
function fillProfileCombo(data) {
alert(data[1].profileName);
}