php - 如何从 AJAX 调用中检索数组?

标签 php sql ajax

我进行了一个 Ajax 调用,需要返回(成功后:...)一个表示 SQL 查询的多维数组:

$.ajax({ url: 'http://localhost/Project/ajaxmethod.php',
                        data: {action: this.title},
                        type: 'post',
                        success: function(data) {

                                    //I need to use the data array here.
                        });

这里是被调用的方法:

<?php

    $bdd = new PDO('mysql:host=localhost;dbname=DATABASE;charset=utf8', 'root', '');


    $req = $bdd->query("SELECT column1, column2, column3 FROM TABLE ");

    $data = ... //Here I need to transform the previous request into a multidimensional array. 
               //For exemple data[3][2] will contain the value within the third row of the second column

    echo $data; //returning the array
}

谢谢

最佳答案

问题

您正在尝试返回数组。但由于 AJAX 调用在 HTTP 协议(protocol)上运行,因此您通常只能传输文本。因此,您的 ajaxmethod.php 将打印数组和呈现的页面,即文本将在显示时返回,而不是数组。

解决方案

使用 json_encode() (PHP) 将数组转换为 JSON 对象并返回。然后使用 JSON.parse() (JavaScript) 在进行 ajax 调用的页面上对其进行解码。这将给出一个数组。

代码

$.ajax({ url: 'http://localhost/Project/ajaxmethod.php',
                        data: {action: this.title},
                        type: 'post',
                        success: function(data) {

                                    //I need to use the data array here.
   var array = JSON.parse(data); //This is the array you want
});

...

<?php

    $bdd = new PDO('mysql:host=localhost;dbname=DATABASE;charset=utf8', 'root', '');


    $req = $bdd->query("SELECT column1, column2, column3 FROM TABLE ");

    $data = ... //Here I need to transform the previous request into a multidimensional array. 
               //For exemple data[3][2] will contain the value within the third row of the second column

    echo json_encode($data) //returning the array
}

关于php - 如何从 AJAX 调用中检索数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47294850/

相关文章:

sql - 表中唯一字段的索引是否允许立即发生选择计数(*)?如果不是,为什么不呢?

sql - 查找引用特定列的存储过程

javascript - 如何从 javascript 图表触发 ajax

JavaScript/JQuery 在加载了 load() 的 html 中不起作用

php - 使用 php jquery ajax 从 mysql 获取图像并将它们显示在 DIV 内的 html 页面中

php - CakePHP 和 Phonegap,它们可以一起使用吗?

php - 在 php 和 mysql 中使用 javascript 进行分页

php - MySQL 查询按月返回行数

javascript - Webkit 仅在调整大小时应用动态加载的 css 样式(通过 ajax)

php - 更新查询在 mysql 中抛出错误