【问题标题】:Ajax Accessing a multidimensional array returned from PHP in JSONAjax以JSON访问从PHP返回的多维数组
【发布时间】:2014-10-20 16:40:37
【问题描述】:

我正在使用 ajax get 方法从我的数据库中返回一些信息。 ajax 方法将已选择的任何类别发送到 php 脚本,该脚本获取我的 products 表中的所有行并将这些行添加到名为 $arr 的变量中。 $arr 是一个多维数组,包含每个项目和该项目的详细信息。

一旦返回到 ajax 成功函数,我真的很难尝试访问这些信息。这是我的 ajax 函数,其中包含我试图用来查看“数据”对象中包含的数据的警报:

$('.category').click(function() {

    var category;

    if ($(this).hasClass('Shirts')) {
        category = 'shirts';
    }
    if ($(this).hasClass('Hats')) {
        category = 'hats';
    }
    if ($(this).hasClass('Acc')) {
        category = 'acc';
    }

    $.ajax({
        type: 'GET',
        url: 'galleryfetch.php',
        data: { 'category' : category },
        dataType: 'json',
        success:  function(data) {


            // alert(data);  Alerts '[object Object]'
            // alert(data[0]); Alerts 'undefined'
            // alert(data[0].ID); Console Error: Cannot read property 'ID' of undefined
            // alert(data.array[0].ID); Console Error: Cannot read property 'ID' of undefined
        }
    });
});

该函数找出点击了哪个类别,然后将其发送到galleryfetch.php脚本,该脚本从数据库中获取该类别的所有行并以JSON格式返回,如下所示:

if ($_SERVER['REQUEST_METHOD'] == 'GET') {

    $category = $_GET['category'];

    $conn = mysqli_connect('localhost', 'root', 'Chan&', 'clothing');   

    $rows = mysqli_query($conn, "SELECT * FROM products WHERE category = '".$category."'");



    while ($row = mysqli_fetch_array($rows)) {

        $arr[] = $row; 
    } 

    echo json_encode(array('data' => $arr));
}

如果我使用 Firebug 调试代码,我可以看到正确的数据肯定包含在“数据”对象中:

如何访问这些数据?

【问题讨论】:

  • 尝试console.log(data);,避免alerts
  • 如果我这样做,它会将对象记录到控制台。我仍然不确定如何访问对象内的各个元素
  • 危险:你很容易受到SQL injection attacks的影响,你需要defend你自己。

标签: php jquery arrays ajax json


【解决方案1】:

您返回的数组有一个键“数据”接收它的同名 javascript 参数/变量。 你应该检查javascript data.data,它是一个数组:

console.log(data.data[0])

【讨论】:

    【解决方案2】:

    根据发布的图片,您会收到一个名为 data 的数组,它由 4 个对象组成。问题在于,在这些对象中的每一个内部,您都在弄乱数字索引和关联索引。我会试试这个:

    success:  function(data) {
    
       // accessing all the properties
       for(var x in data["data"]) {
          for(var y in data["data"][x]) {
             if (y=="ID") {
                alert( "ID of "+x+" is: "+data["data"][x][y] );
             }
          }
       }
    
       // or simply
       alert( data["data"][0]["ID"] );
    
    }
    

    【讨论】:

    • 非常感谢!!真的很挣扎
    • @Mikey,只是一个旁注。由于您将通过其数据库字段名称访问属性,因此请考虑将其称为 mysqli_query($conn,"..query..",MYSQLI_ASSOC);。请注意标志 MYSQLI_ASSOC 以避免同时检索数字和关联字段并因此发送。
    • 好的,我也会这样做:)
    【解决方案3】:

    我认为问题在于您将数据放入名为 data 的键中。所以这应该输出你的预期结果。

    $.ajax({
            type: 'GET',
            url: 'galleryfetch.php',
            data: { 'category' : category },
            dataType: 'json',
            success:  function(data) {
    
                  console.log(data.data[0]);
            }
        });
    

    编辑:如果您使用的是 Google Chrome,我推荐 Postman 插件。这是模拟 AJAX 调用的好方法,尤其是在您使用不太常见的 HTTP 方法(如 PUT 和 DELETE)时。我在尝试开发自己的 API 时经常使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多