![](/img/trans.png)
[英]How to generate dynamic tables with jquery by receiving json response from php
[英]Generate JSON Response from PHP
我是PHP新手。 即时通讯制作移动应用程序,并为此构建网络服务。 从移动即时通讯发送2个参数作为POST,并希望将数据检索为JSON数据。
下面是我的PHP代码。
header('Content-type: application/json');
include 'connection.php';
$response = array();
$location = $_POST['location'];
$country = $_POST['country'];
$query = "SELECT * FROM Feeds WHERE location='".$location."' AND country = '".$country."'";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) != 0)
{
$response["Result"] = 1;
$response["message"] = "Here Data";
}else{
$response["Result"] = 0;
$response["message"] = "No Data";
}
echo json_encode($response);
$conn->close();
当我测试当前响应如下时。
{"Result":1,"message":"Here Data"}
但我也想检索结果数据以及上述响应消息。 像下面
{
"Result": 1,
"Message": "Here Data",
"Feeds": [
{
"userid": "2",
"name": "Demo",
"address": "Demo"
},
{
"userid": "2",
"name": "Demo",
"address": "Demo"
}
]
}
您也希望从SQL查询中得出结果。
header('Content-type: application/json');
include 'connection.php';
$response = array();
$location = $_POST['location'];
$country = $_POST['country'];
$query = "SELECT * FROM Feeds WHERE location='".$location."' AND country = '".$country."'";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) != 0)
{
$response["Result"] = 1;
$response["message"] = "Here Data";
while($feed = mysqli_fetch_array($result, MYSQLI_ASSOC){
$response['Feeds'][] = $feed;
}
}else{
$response["Result"] = 0;
$response["message"] = "No Data";
}
echo json_encode($response);
$conn->close();
这里解决。 您还应该将查询结果推送到$response
数组中。 使用了mysqli_fetch_assoc
函数。 在发送任何实际输出之前,必须先调用header('Content-Type: application/json')
,我建议您将脚本放在末尾,以避免可能的错误
include 'connection.php';
$response = array();
$location = $_POST['location'];
$country = $_POST['country'];
$query = "SELECT * FROM Feeds WHERE location='".$location."' AND country = '".$country."'";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) != 0) {
$response["feeds"] = [];
while ($row = mysqli_fetch_assoc($result)) {
$response["feeds"][] = $row;
}
$response["Result"] = 1;
$response["message"] = "Here Data";
} else {
$response["Result"] = 0;
$response["message"] = "No Data";
}
$conn->close();
header('Content-type: application/json');
echo json_encode($response);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.