如何在一个函数中同时返回包裹编号和注释数?我有两个单独的 sql 字符串返回不同的结果。我希望能够返回 apn 编号并将值放入标签中以及有多少评论。这可能吗?我该怎么做?
Jquery:
$.ajax({
url: "classes/get-apn-count-comments.php?parcel_id=" + parcel_id,
type: "GET",
data: { parcel_id : parcel_id },
dataType: 'json',
error: function(SMLHttpRequest, textStatus, errorThrown){
alert("An error has occurred making the request: " + errorThrown);
},
success: function(data2){
//do stuff here on success
//$('#ParcelNumber').html(data[0]["apn"]);
$('#ViewComments').val('View ' + data2[0].count + ' Comments');
}
});
.PHP:
<?php
require_once('../config.php');
if(isset($_GET['parcel_id'])) {
$db = new ezSQL_mysql(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
//get the apn based on id
//$data = $db->get_results("select apn from parcels where parcel_id=" . $_GET['parcel_id']);
//if($data != null) echo json_encode($data);
//count number of comments for the id
$data2 = $db->get_results("select count(*) as count from comments where parcel_id=" . $_GET['parcel_id']);
echo json_encode($data2);
}
?>
在 php 端创建一个数组来保存答案一和答案二。然后json_encode并回显新的多维数组,就像使用旧数组一样。
然后在回调的javascript端运行JSON.parse()将数组转换为javascript对象。
例:
if(isset($_GET['parcel_id'])) {
$db = new ezSQL_mysql(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
$return = array();
//get the apn based on id
$data = $db->get_results("select apn from parcels where parcel_id=" . $_GET['parcel_id']);
if($data != null){
$return['data_one'] = $data;
}
//count number of comments for the id
$data2 = $db->get_results("select count(*) as count from comments where parcel_id=" .$_GET['parcel_id']);
if($data2 != null){
$return['data_two'] = $data2;
}
echo json_encode($return);
}
.js:
success: function(res){
//do stuff here on success
res = JSON.parse(res);
console.log(res);
}