从PHP到AJAX获取数组

时间:2013-03-27 14:09:36

标签: php javascript ajax jquery

我想从PHP检索一组数组到ajax。我的代码没有返回任何东西,有人可以帮助我如何从PHP检索到ajax的值。如果我不在mysql_fetch中创建数组,它将从数据库中检索最后一个值并将其传递给ajax函数。我想获得整个价值观。我怎么能这样做?

AJAX代码:

<script>
  //Global Variables
  var channel;
 function overall(){
    $(".one").show();
    $(".two").hide();
    $(".three").hide();
    $(".four").hide();
    window['channel']="overall";
     $.ajax({
             type:"GET",
             url:"dash2.php",
             data:{channel:channel},
             dataType:'json',
             success:function(data){
                    console.log(data.a);
                    console.log(data.b);
                    console.log(data.c);
                    }
            });
    }
</script>

PHP代码:

<?php
   error_reporting(0);
   $channel=$_GET['channel'];
    $host="192.168.0.29";
    $username="root";
    $password="root";
    $dbname="realcl";
  mysql_connect($host,$username,$password)
    OR DIE ('Unable to connect to database! Please try again later.');
    mysql_select_db($dbname);
    $query = 'select * from '.$channel;
    $masterresult = mysql_query($query);
    $success[];
    $timeout[];
    $fail[];

    while($row1 = mysql_fetch_array($masterresult))
    {
        $success[]=$row1[1];
        $timeout[]=$row1[2];
        $fail[]=$row1[3]; 
    }

    echo json_encode(array("a"=>$success,"b"=>$timeout,"c"=>$fail));
?>

1 个答案:

答案 0 :(得分:0)

这将导致致命错误(因此,无效的json ......):

$success[];
$timeout[];
$fail[];

你可能想要:

$success = array();
// etc.

你有一个巨大的SQL注入问题,你应该根据允许的表名的白名单检查你的表名。您还应该切换到PDO(或mysqli),因为mysql_*函数已被弃用。