【问题标题】:Repeat JavaScript AJAX request until status change重复 JavaScript AJAX 请求直到状态改变
【发布时间】:2015-06-11 11:51:40
【问题描述】:

我正在使用 AJAX 从 PHP 文件中进行和检索 API 调用,然后使用 jQuery IF 语句来显示某些数据。

返回的数据有几种不同的状态,例如:“就绪”、“进行中”、“DNS”和“错误”。每个状态都有一条消息。

对于一个特定的状态,“进行中”,我想继续循环浏览 JavaScript 函数,直到状态更改为其他状态。如果状态为“进行中”,它最多可能需要 1 分钟才能更改,因此如果可能,我想以 5 秒的间隔循环浏览 JavaScript 函数。

我在下面包含了我的 jQuery。

    $(document).ready(function() {

    //Stops the submit request
    $("#myAjaxRequestForm").submit(function(e){
           e.preventDefault();
    });

    //checks for the button click event
    $("#myButton").click(function(e){
           $("#ajaxResponse").empty();
            //get the form data and then serialize that
            dataString = $("#myAjaxRequestForm").serialize();

            //get the form data using another method
            var hostName = $("input#hostName").val();
            dataString = "host=" + hostName;

            //make the AJAX request, dataType is set to json
            //meaning we are expecting JSON data in response from the server
            $.ajax({
                type: "GET",
        url: "api.php",
                data: dataString,
                dataType: "json",

                //if received a response from the server
                success: function( response ){
                var data = response.status;
                    if ((data == 'READY' && response.endpoints[0].statusMessage == 'Ready' )) {
                    $("#ajaxResponse").append("<b>Status:</b> " + response.endpoints[0].statusMessage+ "<br>");
                    $("#ajaxResponse").append("<b>Host:</b> " + response.host+ "<br>");
                    $("#ajaxResponse").append("<b>Port:</b> " + response.port+ "<br>");
                    $("#ajaxResponse").append("<h3>Endpoint [0]</h3><b>Server Name:</b> " + response.endpoints[0].serverName+ "<br>");
                    $("#ajaxResponse").append("<b>IP Address:</b> " + response.endpoints[0].ipAddress+ "<br>");
                    $("#ajaxResponse").append("<b>Grade:</b> " + response.endpoints[0].grade+ "<br>");
                    $("#ajaxResponse").append("<h3>Endpoint [1]</h3><b>Server Name:</b> " + response.endpoints[1].serverName+ "<br>");
                    $("#ajaxResponse").append("<b>IP Address:</b> " + response.endpoints[1].ipAddress+ "<br>");
                    $("#ajaxResponse").append("<b>Grade:</b> " + response.endpoints[1].grade+ "<br>");
                    $("#ajaxResponse").append("<h3>Endpoint [2]</h3><b>Server Name:</b> " + response.endpoints[2].serverName+ "<br>");
                    $("#ajaxResponse").append("<b>IP Address:</b> " + response.endpoints[2].ipAddress+ "<br>");
                    $("#ajaxResponse").append("<b>Grade:</b> " + response.endpoints[2].grade+ "<br>");
                     }
                    else if ((data == 'READY' && response.endpoints[0].statusMessage != 'Ready')) {
                        $("#ajaxResponse").append("<b>Status: </b>" +response.endpoints[0].statusMessage+ "<br>");
                        $("#ajaxResponse").append("<b>Server Name: </b>" + response.endpoints[0].serverName+ "<br>");
                        $("#ajaxResponse").append("<b>IP Address: </b>" + response.endpoints[0].ipAddress+ "<br>");
                     }
                     else if (data == "DNS") {
                         $("#ajaxResponse").html("<div><b>No cached result found.<br><br>" +response.statusMessage+ "<br>..please wait a few mins and try again.</b></div>");
                     }
                     else if (data == "IN_PROGRESS") {
                         $("#ajaxResponse").html("<div><b>No cached result found.<br><br>" +response.endpoints[0].statusMessage+ "<br>..please wait a few mins and try again.</b></div>");
                     }
                     else if (data == "ERROR") {
                         $("#ajaxResponse").html("<div><b>Error.<br><br>" +response.statusMessage+ "<br></b></div>");
                     }
                     else {
                         $("#ajaxResponse").html("<div><b>error</b></div>");
                     }
                },

            });       
    });

});

【问题讨论】:

  • cycle through 是什么意思?继续发出 ajax 请求?
  • 是的,没错。继续进行 ajax 调用。
  • 仅供参考-当您开始多次重复相同的选择器时,最好将其缓存起来,这样就不必每次都进行 DOM 搜索。 DOM 搜索很昂贵

标签: php jquery ajax curl


【解决方案1】:

将 AJAX 请求移至函数(例如 doAjax()),以便您可以根据需要调用它。单击按钮时调用 doAjax()。当返回状态为“In Progress”时,使用 setTimeout() 在 5 秒后递归调用相同的函数。

AJAX 请求大约每 5 秒发出一次,直到状态不是“进行中”。 (我说“大致”是因为 AJAX 请求本身需要时间,并且 5 秒延迟在请求完成后开始。)

更新的 JavaScript:

$(document).ready(function () {

    //Stops the submit request
    $("#myAjaxRequestForm").submit(function (e) {
        e.preventDefault();
    });

    //checks for the button click event
    $("#myButton").click(function (e) {
        e.preventDefault(); // Prevent default button click action
        doAjax();
    });

});

function doAjax() {
    //$("#ajaxResponse").empty(); Move this to reduce appearance of refreshing
    //get the form data and then serialize that
    dataString = $("#myAjaxRequestForm").serialize();

    //get the form data using another method
    var hostName = $("input#hostName").val();
    dataString = "host=" + hostName;

    //make the AJAX request, dataType is set to json
    //meaning we are expecting JSON data in response from the server
    $.ajax({
        type: "GET",
        url: "api.php",
        data: dataString,
        dataType: "json",

        //if received a response from the server
        success: function (response) {
            var data = response.status;
            if ((data == 'READY' && response.endpoints[0].statusMessage == 'Ready')) {
                $("#ajaxResponse").empty();
                $("#ajaxResponse").append("<b>Status:</b> " + response.endpoints[0].statusMessage + "<br>");
                $("#ajaxResponse").append("<b>Host:</b> " + response.host + "<br>");
                $("#ajaxResponse").append("<b>Port:</b> " + response.port + "<br>");
                $("#ajaxResponse").append("<h3>Endpoint [0]</h3><b>Server Name:</b> " + response.endpoints[0].serverName + "<br>");
                $("#ajaxResponse").append("<b>IP Address:</b> " + response.endpoints[0].ipAddress + "<br>");
                $("#ajaxResponse").append("<b>Grade:</b> " + response.endpoints[0].grade + "<br>");
                $("#ajaxResponse").append("<h3>Endpoint [1]</h3><b>Server Name:</b> " + response.endpoints[1].serverName + "<br>");
                $("#ajaxResponse").append("<b>IP Address:</b> " + response.endpoints[1].ipAddress + "<br>");
                $("#ajaxResponse").append("<b>Grade:</b> " + response.endpoints[1].grade + "<br>");
                $("#ajaxResponse").append("<h3>Endpoint [2]</h3><b>Server Name:</b> " + response.endpoints[2].serverName + "<br>");
                $("#ajaxResponse").append("<b>IP Address:</b> " + response.endpoints[2].ipAddress + "<br>");
                $("#ajaxResponse").append("<b>Grade:</b> " + response.endpoints[2].grade + "<br>");
            } else if ((data == 'READY' && response.endpoints[0].statusMessage != 'Ready')) {
                $("#ajaxResponse").empty();
                $("#ajaxResponse").append("<b>Status: </b>" + response.endpoints[0].statusMessage + "<br>");
                $("#ajaxResponse").append("<b>Server Name: </b>" + response.endpoints[0].serverName + "<br>");
                $("#ajaxResponse").append("<b>IP Address: </b>" + response.endpoints[0].ipAddress + "<br>");
            } else if (data == "DNS") {
                $("#ajaxResponse").html("<div><b>No cached result found.<br><br>" + response.statusMessage + "<br>..please wait a few mins and try again.</b></div>");
            } else if (data == "IN_PROGRESS") {
                $("#ajaxResponse").html("<div><b>No cached result found.<br><br>" + response.endpoints[0].statusMessage + "<br>..please wait a few mins and try again.</b></div>");
                // Call this function again after 5 seconds
                setTimeout(function () {
                    doAjax();
                }, 5000);
            } else if (data == "ERROR") {
                $("#ajaxResponse").html("<div><b>Error.<br><br>" + response.statusMessage + "<br></b></div>");
            } else {
                $("#ajaxResponse").html("<div><b>error</b></div>");
            }
        },

    });
}

【讨论】:

  • 完美运行.. 想知道是否有办法在不清除 div 的情况下实现这一点,而是更新 response.endpoints[0].statusMessage 值。现在,如果我不清除 div,它将继续为每个状态更改添加一个额外的行,因为我只想要最新消息
  • response.endpoints[0].statusMessage 应该只被读取 - 我无法想象你为什么要更新它。你想更新哪个 div,你想要什么?
  • 对不起,如果我不清楚。我想阅读它,但当它在 jquery 中循环时,我只希望它显示最新值。现在,我通过在每个周期清除 div 来实现这一点。如果我不清除 div,则以前的值将保留在页面上。现在唯一的问题是当 div 被清除时,页面看起来像是在刷新。不是一个大问题,但如果我能找到一种替代方法而不是清除 div 看起来会更好.. 有问题的 div 是#ajaxResponse
  • 查看更新后的答案。看起来令人耳目一新,因为您在 AJAX 请求开始之前清除了 div,并在请求完成后填充它。请求需要时间,在此期间 div 将显示为空白。我已经更新了我的答案,只在请求结果返回后清除 div,除非实际状态发生变化,否则应该防止任何明显的 div 清除。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-28
  • 1970-01-01
  • 2016-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多