我有一个简单的服务器发送的事件设置,试图将其显示为表格。目前,我有SSE php页面,将数据从MySQL表中提取出来,并将数据作为Json数组发送到实时页面。我如何能够采用Json数组并将其放入html表中,而又不将数组作为帖子发回并导致页面“刷新”?

这是我当前的代码

SSE.php

//get MySQL data
$new_data = getVar();
//Create Array
$data_array = array();
//add data to array
while($row = $new_data->fetch_assoc()){
    $data_array[] = $row;
    $out = array_values($data_array);
    $new_out = json_encode($out);
}
//echo the array to html page
echo "data: $new_out \n\n }'";


Index.html

<script type="text/javascript">
 //check for browser support
 if(typeof(EventSource)!=="undefined") {
 //create an object, passing it the name and location of the server side script
var eSource = new EventSource("send_sse.php");
//detect message receipt
eSource.onmessage = function(event) {
    //write the received data to the page
    //document.getElementById("serverData").innerHTML = event.data;
};


其中serverData是当前显示数组的div

我试图回显数据:多次或回显html标记,但是我无法使其工作并且没有php运行时错误

谢谢

最佳答案

您可能要向PHP脚本提出AJAX请求。这将允许数据库表中的数据填充页面而无需刷新。检出this W3Schools example

您可以使用jQuery's AJAX functions简化用户定义的JavaScript(尽管您也必须将jQuery加载到页面上)。

09-04 18:31
查看更多