php - AJAX 请求到 php 上的无限循环
问题描述
我有一台正在运行并等待数据的服务器
while(true){
$r = socket_recvfrom($sock, $messageRecieved, 512, 0, $remote_ip, $remote_port);
....
....
....
$jsonData = array("Name" => $sensor->getName(), "Value" => $sensor->getValue(), "Tipology" => $sensor->getTipology(), "Timestamp" => $sensor->getTimestamp());
echo json_encode($jsonData);
}
然后我对该脚本有一个 Ajax 请求
$(document).ready(function () {
$.ajax({
type: "POST",
url: "../serverScript.php",
dataType:'json',
success: function (response, textStatus, xhr) {
response["Name"] = response["Name"].replace(/\s/g, '');
divId = $('#' + response["Name"]);
if (!divId.length){
$('#serverResult').append('' +
'<div class="col-sm-4 shadow-lg p-3 mb-5 bg-white rounded one marginTop-1" id = "' + response["Name"] + '">' +
'<h3 class="d-flex justify-content-center">' + response["Name"] + '</h3>' +
'</div>'
);
}
$("#"+response["Name"]).append(response["Tipology"] + " " + response["Value"] + " " + response["Timestamp"]);
},
error: function (xhr, ajaxOptions, thrownError) {
console.warn(xhr.responseText);
alert(xhr.status);
alert(thrownError);
}
});
});
抱歉代码不好,Ajax 请求和 Php 脚本都会变得更好,我只需要先让事情正常工作!
我的问题是:
当我从服务器代码中删除 while 并只执行一次循环迭代时,Ajax 请求可以完美运行。问题是我希望对从服务器收到的每条消息都有一个 Ajax 请求。所以,基本上,我需要一种在 while 循环中使用 Ajax 请求的方法。无论如何要这样做?
谢谢!
解决方案
推荐阅读
- python - Matplotlib:如何根据列值为散点图圆圈赋予颜色
- azure-service-fabric - SF - 高可用性选项?
- node.js - node.js express - 如何将 POST 正文参数传递回原始表单以在失效时重新填充?
- excel - 在 Excel VBA 中识别字符串模式
- android - 如何在android中解析从BLE设备接收到的字节数据
- java - 如何显示在后台运行的应用程序以及我们如何停止它们的操作?
- html - 自定义单选按钮边框颜色
- python - Raspberry Pi cv2.VideoCapture 在第二次以相同的 id 初始化时卡住
- sql - 使用 where 条件获取记录,该条件指定在 DB2 中获取本周的记录
- .net - 实体框架身份验证提供程序 - 更新默认连接