修改
我需要将两个获取的数组放入一个数组中,然后使用echo json_encode
将其发送回AJAX
。
这是我的PHP代码:
header('Content-Type: application/json');
$arr = array();
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
$date1 = $_POST['current_year'];
//$res = array();
$c = "cash";
$i = "installment";
//SUM of cash paid Month
$sql = "SELECT
count(app_id) as patients,
t.m as month
FROM (
SELECT 1 AS m UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION
SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION
SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) AS t
LEFT JOIN dentist.appointment ON t.m = month(date_app) AND
id_logged = :logged AND year(date_app) = :year_now
GROUP BY t.m";
$sqlStmt = $conn->prepare($sql);
$sqlStmt->bindValue(":logged", $id_logged);
$sqlStmt->bindValue(":year_now", $date1);
$exec = $sqlStmt->execute();
$res1 = $sqlStmt->fetchAll();
$sql2 = "SELECT
count(app_id)+1 as patients,
t.m as month
FROM (
SELECT 1 AS m UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION
SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION
SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) AS t
LEFT JOIN dentist.appointment ON t.m = month(date_app) AND
id_logged = :logged AND year(date_app) = :year_now
GROUP BY t.m";
$sqlStmt2 = $conn->prepare($sql2);
$sqlStmt2->bindValue(":logged", $id_logged);
$sqlStmt2->bindValue(":year_now", $date1);
$exec2 = $sqlStmt2->execute();
$res2 = $sqlStmt2->fetchAll();
$res['one']=$res1;
$res['two']=$res2;
echo json_encode($res);
这里是XHR的答复:
现在在AJAX脚本中,我需要获取数组的每个部分,以便我可以在图表上显示它:
success:function(res)
{
var patientData = [];
$.each(res, function( key, row)
{
patientData.push(row['one']);
console.log(patientData);
});
//Bar Chart Script;
}
但我无法在控制台和条形图上看到任何数据。控制台的结果是undefined
:
答案 0 :(得分:1)
以下是如何操作:
success: function(data){
var patientData = [];
var res = $.parseJSON(data);
$.each(res, function(index, element) {
alert(res[index]);
patientData.push(res[index]);
});
}
答案 1 :(得分:1)
您将获得a = [i for i in range(1,11)]
#a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = [a[i]+1 if i%2==1 else a[i] for i in range(len(a))]
#b = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11]
中的密钥(“one”,“two”,...)和key
中的行数据
由于$ .each在第一个参数中返回对象属性名称(
row
),在第二个参数中返回属性key
,所以我们如下:
value
例如,我们可以像这样检查结果
success:function(res){
var res = $.parseJSON(res);
console.log(res);
var patientData = [];
$.each(res, function (key, row){
patientData.push(row);
console.log(patientData);
});
//Bar Chart Script;
}
$.each({"one":[1, 2, 3, 4], "two":[5, 6, 7, 8]}, function (key, value){
console.log(key, value);
/* write to document */
document.write("<br>");
document.write("Key:" + key);
document.write(", Value:" + value);
});
答案 2 :(得分:0)
尝试:
success:function(res)
{
var res = $.parseJSON(res);
console.log(res);
var patientData = [];
$.each(res, function (key, row)
{
patientData.push(row.one);
console.log(patientData);
});
//Bar Chart Script;
}