首页 > 解决方案 > 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 请求的方法。无论如何要这样做?

谢谢!

标签: phpajax

解决方案


推荐阅读