Php 如何从AJAX调用中检索数组?
我进行了一个Ajax调用,需要返回(成功后:…)一个表示SQL查询的多维数组:Php 如何从AJAX调用中检索数组?,php,sql,ajax,Php,Sql,Ajax,我进行了一个Ajax调用,需要返回(成功后:…)一个表示SQL查询的多维数组: $.ajax({ url: 'http://localhost/Project/ajaxmethod.php', data: {action: this.title}, type: 'post', success: function(data) {
$.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
}
不能只回显数组(不能,它是数组而不是简单的值)
幸运的是,有一种叫做JSON的东西。在PHP中,您将所有需要的信息(在本例中,是数据库中的行)存储在一个大数组中,然后执行echo json\u encode($array)代码>
在Javascript端,您将$.ajax
更改为$.getJSON
,这样jQuery也能理解我们所说的JSON,等等,您的PHP数组有一个很好的Javascript版本
然后是javascript
$.getJSON(
'http://localhost/Project/ajaxmethod.php',
{action: this.title},
function(response) {
// And in 'response' you now have a ready to use JS object)
console.log(response);
});
*如果确实需要,您还可以使用$.ajax()
,只需添加一个数据类型:“json
问题
您正在尝试返回am数组。但由于AJAX调用在HTTP协议上工作,所以通常只能传输文本。因此,您的ajaxmethod.php将打印数组和呈现的页面,即文本将在显示时返回,而不是数组
解决方案
使用JSON_encode()(PHP)将数组转换为JSON对象,并返回该对象。然后在发出ajax调用的页面上使用JSON.parse()(JavaScript)对其进行解码。这将生成一个数组
代码
$.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
});
$.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
}