当前,我正在进行ajax调用,它以json格式返回我的数据。但是我需要执行多个查询,并以单独的变量/数组返回这些查询的结果。如何执行查询以这种方式返回数据,以及如何在ajax中接收数据?
感谢您的帮助。
$query1 = "SELECT `user`, `age` FROM `users` WHERE `GENDER`= 'M';
$query2 = "SELECT `user`, `age` FROM `users` WHERE `GENDER`= 'F';
$result1 = $connection->query($query1) or die ("error");
$data1 = array();
//loop through the returned data
foreach ($result1 as $row) {
$data1[] = $row;
}
//close connection
$connection->close();
print json_encode($data1);
答案 0 :(得分:1)
在php中,您必须将所有数组分配给单个数组并对该数组进行编码
例如:
foreach ($result1 as $row) {
$data1[] = $row;
}
$data['array1']=$data1;
foreach ($result2 as $row) {
$data2[] = $row;
}
$data['array2']=$data2;
foreach ($result3 as $row) {
$data3[] = $row;
}
$data['array3']=$data3;
echo json_encode($data);
答案 1 :(得分:0)
http://php.net/manual/en/function.array-merge.php
$data1 = [ ... ]; // array with data
$data2 = [ ... ]; // array with some other data
echo json_encode(array_merge($data1, $data2));
编辑:
echo json_encode(array(
'data1' => $data1,
'data2' => $data2
));
在javascript中,您可以执行response.data1
和response.data2
$.ajax({
url: "testdata.php",
method: "POST",
success: function(data) {
var obj = JSON.parse(data);
obj.data1;
obj.data2;
}
});