gpt4 book ai didi

php - 如何在json中编码php数组并解析为jquery

转载 作者:可可西里 更新时间:2023-11-01 08:59:24 24 4
gpt4 key购买 nike

我正在使用 ajax 调用通过下拉获取记录,但问题是它只获取了一条记录,而数据库中有三条记录

这是我的 PHP 代码:

<?php
include 'config/dbconfig.php';

$genid = $_POST['id'];
$operatorId = $_POST['operatorId'];

$query = mysqli_query($con, "SELECT * FROM generatorrun WHERE generatorId='$genid' AND operatorId='$operatorId'");
while($result = mysqli_fetch_array($query)) {

$turnOn = $result['startTime'];
$turnOff = $result['endTime'];
$datetime1 = new DateTime($turnOn);
$datetime2 = new DateTime($turnOff);
$interval = $datetime1->diff($datetime2);
$datedifference = $interval->format('%Y-%m-%d %H:%i:%s');
$startReading = $result['startReading'];
$endReading = $result['endReading'];
$dailyConsumption = $endReading - $startReading;

$postData = array(
"turnOn" => $turnOn,
"turnOff" => $turnOff,
"runningTime" => $datedifference,
"startReading" => $startReading,
"endReading" => $endReading,
"dailyConsumption" => $dailyConsumption,
);
}

echo json_encode($postData);
?>

我必须从 MySQL 中获取值并将其存储在关联数组中,然后使用 json_encode() 函数对其进行编码。

这是在 jquery 中获取记录的代码:

<script>
$(document).ready(function () {
$(".bg-yellow").hide();
$(".bg-red").hide();
$("#getGen").change(function () {

var id = $('#getGen').val();
var operatorId = $(".opid").val();
$.ajax({
type: "POST",
url: 'getGenerator.php',
data: {id: id, operatorId: operatorId},
success: function (response) {
var data = jQuery.parseJSON(response);
$(".turnOn").html(data.turnOn);
$(".turnOff").html(data.turnOff);
$(".running").html(data.runningTime);
$(".startReading").html(data.startReading);
$(".endReading").html(data.endReading);
$(".dailyConsumption").html(data.dailyConsumption);
$(".bg-yellow").show();
$(".bg-red").show();
}
});
});
});
</script>

问题是它只获取了一条记录,我使用 while 循环遍历了 MySQL 表中的所有记录,但它只获取了一条记录

最佳答案

在您的 while 循环中,您正在分配变量。所以每个循环都会覆盖这些值。您必须使用 array_push

$postData = array();
while($result=mysqli_fetch_array($query)){
$turnOn=$result['startTime'];
$turnOff=$result['endTime'];
$datetime1 = new DateTime($turnOn);
$datetime2 = new DateTime($turnOff);
$interval = $datetime1->diff($datetime2);
$datedifference=$interval->format('%Y-%m-%d %H:%i:%s');
$startReading=$result['startReading'];
$endReading=$result['endReading'];
$dailyConsumption=$endReading-$startReading;
array_push($postData,array(
"turnOn" => $turnOn,
"turnOff" => $turnOff,
"runningTime"=>$datedifference,
"startReading"=>$startReading,
"endReading"=>$endReading,
"dailyConsumption"=>$dailyConsumption
));
}

关于php - 如何在json中编码php数组并解析为jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49530706/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com