【问题标题】:Get array from PHP to AJAX [duplicate]从PHP获取数组到AJAX [重复]
【发布时间】:2013-03-27 14:09:35
【问题描述】:

我想从 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));
?>

【问题讨论】:

  • @undefined 这是完全重复的
  • 这个问题是关于在 ajax 中使用数组没有解决类型问题
  • 当有人以dual where 0; drop database realcl;-- 输入channel 时会发生什么

标签: php javascript ajax jquery


【解决方案1】:

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

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

你可能想要:

$success = array();
// etc.

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

【讨论】:

  • 知道它会给我一个错误:(你能帮我修改 ajax 以接收多个值
  • @jibindcruz 就像我在答案中指定的那样更改它。
  • 看到这是针对 php 部分的吧?我将如何为 ajax 更改它?
猜你喜欢
  • 1970-01-01
  • 2017-01-22
  • 1970-01-01
  • 2023-03-17
  • 2017-05-25
  • 2018-05-01
  • 2016-05-27
  • 2017-10-17
  • 1970-01-01
相关资源
最近更新 更多