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

Posted

技术标签:

【中文标题】如何在json中编码php数组并解析成jquery【英文标题】:How to encode php array in json and parse into jquery 【发布时间】:2018-09-06 21:56:48 【问题描述】:

我正在使用 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 表中的所有记录,但它只获取一条记录

【问题讨论】:

$postData[] = array(。你知道[] 是什么意思吧? 是的,我也尝试过这种方式,但结果是一样的 是什么意思——一样?您在控制台中看到了什么?如果您有一系列项目 - 您需要遍历它们。 您的脚本对SQL Injection Attack 甚至if you are escaping inputs, its not safe! 都开放使用prepared parameterized statements 【参考方案1】:

在您的 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
    ));
  

【讨论】:

如何在json中解析这种数组 如何解析成jquery【参考方案2】:

你只需要定义一个数组。

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

$postData = array();
$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);
?>

【讨论】:

这个方法的json解析是空的 我的 json 为空 使用 document.write(response);用于测试响应 我可以使用警报吗? 你还需要在查询中使用for循环【参考方案3】:

试试这个:

include 'config/dbconfig.php';
$genid      = $_POST['id'];
$operatorId = $_POST['operatorId'];
$query = mysqli_query($con, "SELECT * FROM generatorrun WHERE generatorId='$genid' AND operatorId='$operatorId'");
$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;

$postData[] = array( // this is you missed here
        "turnOn"           => $turnOn,
        "turnOff"          => $turnOff,
        "runningTime"      => $datedifference,
        "startReading"     => $startReading,
        "endReading"       => $endReading,
        "dailyConsumption" => $dailyConsumption,
);

它会给你多个结果集。

【讨论】:

以上是关于如何在json中编码php数组并解析成jquery的主要内容,如果未能解决你的问题,请参考以下文章

php数组转换成json格式后汉字怎么就被解析成字母了啊

如何在 Jquery 中使用 JSON?

如何在PHP中解析json

如何在 jQuery 中解析 JSON 数组?

快速解析双 JSON 编码数组并访问它

如何使用json方法解析android中没有键名的数组内的嵌套json编码数组?