在 PHP 变量中使用 JSON 的结果


Using the result of JSON in PHP variables

完全重写我的问题

我正在尝试执行的任务是在不重新加载整个页面的情况下更新五个变量的显示。

我有一个 php 文件 (check_conf_update.php),它运行一个生成数据的查询,我正在将其编写成 JSON 脚本。在运行我最后的查询的 PHP 文件中:

echo json_encode($record);

JSON 结果如下所示:

[{"ClientName":"Another","RoomFromDateTime":"2016-02-25 01:00:00","RoomToDateTime":"2016-03-13 23:00:00","ClientImageName":"anothernew.png","DisplayText":"System Testing"}]

我现在需要在名为"template.php)的页面上使用数据。如何从 Json 结果中读取数据并在变量中分配每个结果元素,我可以在"模板.php"页面上使用。我需要 Json 脚本每 x 秒运行一次,以便显示始终显示最新信息。

我有五个 php 变量:

$CientName
$ImageName
$DisplayText
$FromTime
$ToTime 

我在我的网页上使用它来在与下面的脚本相同的页面上显示数据。

$(document).ready(function() { 
    function runupdate() { 
       $.ajax({ 
         url: 'check_conf_update.php',
         type: 'GET',
         data: 'record',
         dataType: 'json',
            success: function(data){ 
                // not sure what I need to do here
             } 
         });  
    };  
    // run it initially
    runupdate();
    // run it every 30 seconds
    setInterval(runupdate, 30 * 1000);
});

对不起,如果让任何人感到困惑,看起来我做到了。

谁能帮忙。提前感谢您的时间。

问候

目前还不清楚生成数据的 PHP 脚本中会发生什么。如果您也可以使用PHP的完整代码更新帖子,那将很有帮助。但是,我假设您想使用生成的 json 字符串中的数据来填充目标文件 (check_conf_update.php) 中的 PHP 变量?在这种情况下,

// check_conf_update.php
// $_POST['record'] == '[{"ClientName":"Another","RoomFromDateTime":"2016-02-25 01:00:00","RoomToDateTime":"2016-03-13 23:00:00","ClientImageName":"anothernew.png","DisplayText":"System Testing"}]'
$json = $_POST['record'];
$array = json_decode($json, true)[0];
$ClientName = $array['ClientName'];
$ImageName = $array['ClientImageName'];
$DisplayText = $array['DisplayText'];
$FromTime = $array['RoomFromDateTime'];
$ToTime = $array['RoomToDateTime'];
echo $ClientName . ', ' . $ImageName . ', ' . $DisplayText . ', ' . $FromTime . ', ' . $ToTime;

编辑:

template.php文件中的所有 PHP 代码在浏览器中呈现之前都在服务器端运行,因此届时将更新的 json 数据分配给 PHP 变量为时已晚。在不重新加载页面的情况下更新信息的唯一方法是用javascript替换文本或元素。每次成功的 ajax 请求后,您可以更新页面中的值,

$('.clientname').html(data[0].ClientName);
$('.childbox').html(data[0].ClientImageName);
$('.clientndisplaytext').html(data[0].DisplayText);
$('.clientndisplaytime').html(data[0].RoomFromDateTime);
$('.clientndisplaytime').html(data[0].RoomToDateTime);