使用jquery ajax返回和接收多个查询的结果

问题描述 投票:1回答:2

目前,我正在进行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);
php jquery json ajax
2个回答
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);

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.data1response.data2

$.ajax({
            url: "testdata.php",
            method: "POST",
            success: function(data) {
              var obj = JSON.parse(data);
              obj.data1;
              obj.data2;
            } 
});
© www.soinside.com 2019 - 2024. All rights reserved.