我用 PHP 制作了一个 RESTful API。很快,我可以通过调用像 http://api.website.com/addInfos 这样的地址来注册一些信息。

此请求是 POST 请求。这是我的方法:

文件:api.php

<?php 
 
/* Page api.php */ 
 
private function addInfos() 
{ 
 
// Check if it's a POST request and if all fields are correct 
// Insert data in my MySQL database 
 
// TODO: make an automatic refresh for page named infos.php 
 
} 
 
?> 

第二个文件,其中显示来 self 的数据库的数据:

文件:infos.php

<?php 
 
/* Page infos.php */ 
 
// Connection to database 
// Prepare the request using PDO 
// Execute the request 
// Display infos in a while loop 
 
?> 

我的问题是:如何在调用 API 的“AddInfos”函数后刷新显示数据的代码部分?

编辑1:

这是我能做的:

文件:index.php

<!DOCTYPE html> 
<html lang="fr"> 
<head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <meta name="description" content=""> 
    <title></title> 
 
    <script src="js/jquery.js"></script> 
 
</head> 
 
<body> 
 
<div id="infos"></div> 
 
<script> 
 
        function displayInfo(r) {  
 
            $.post("infos.php", 
               { refresh : r}, 
               function(data){ 
                 //alert("Data Loaded: " +  data); 
                 $("#infos").html(data);  
 
               } 
             ); 
        }  
 
        $(document).ready(function() { 
            displayInfo(1);  
 
            $('a.info_link_text').click(function(){ 
                alert($(this).text()); 
            }); 
 
        }); 
 
    </script> 
 
</body> 
 
</html> 

文件:infos.php

<?php 
 
require_once('database.php'); 
 
 if(isset($_POST['refresh'])){ 
 
        $selectInfos = getAllInfos(); 
        $selectInfos->execute(); 
 
        echo "<table>"; 
                    echo "<th>User</th>"; 
                    echo "<th>Email</th>"; 
 
        while($row = $selectInfos->fetch(PDO::FETCH_OBJ)){ 
 
                $fullname = $row->user_fullname; 
                $email = $row->user_email; 
 
                    echo "<tr>"; 
                        echo "<td>".$fullname."</td>"; 
                        echo "<td>".$email."</td>"; 
                    echo "</tr>"; 
 
 
        } 
 
        echo "</table>";     
} 
 
?> 

当我加载index.php时,我可以从页面infos.php获取信息。但我真的不知道当我的API的“addInfos”方法被调用时我该怎么做,因为我需要在infos.php上发出POST请求(没问题),但将结果数据放在index.php上(不行,我不知道该怎么做)。请问您能让我知道如何实现这一目标吗?

非常感谢您的帮助。

最诚挚的问候, 拉皮努。

请您参考如下方法:

我认为你需要的是一个基于WebSocket HTML5的库。服务器可以保留并向所有同时连接的客户端发送通知。然后在您的 JavaScript 处理程序中,您可以处理任何您想要的内容。

在 PHP 中,您可以尝试这些示例 WebSocket HTML5 PHP on Google

另一种方法是定期向服务器发送多个 REST 查询来更新您的页面,但您似乎只需要实时更新。


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!