Javascript 如何在ajax中检查和重新检查,并等待服务器消息的值更改?

Javascript 如何在ajax中检查和重新检查,并等待服务器消息的值更改?,javascript,jquery,ajax,Javascript,Jquery,Ajax,我正在使用一个应用程序,当用户单击应用程序中的“保存”按钮时,它会保存信息并重新启动服务器。 表单必须在ajax成功启动之前成功提交。如果表单中的信息保存正确,我将从服务器收到200条成功消息 如果服务器重新启动成功(200),当服务器重新启动或正在重新启动时,会发出500条内部服务器消息,重新启动服务器大约需要30到40秒或更长时间,因此我有30秒的等待时间。。 一旦服务器重新启动,它将发出一条200成功服务器消息 目前,我正在使用Ajax调用2检查服务器重启数据提交是否成功,并使用另一个Aj

我正在使用一个应用程序,当用户单击应用程序中的“保存”按钮时,它会保存信息并重新启动服务器。 表单必须在ajax成功启动之前成功提交。如果表单中的信息保存正确,我将从服务器收到200条成功消息

如果服务器重新启动成功(200),当服务器重新启动或正在重新启动时,会发出500条内部服务器消息,重新启动服务器大约需要30到40秒或更长时间,因此我有30秒的等待时间。。 一旦服务器重新启动,它将发出一条200成功服务器消息

目前,我正在使用Ajax调用2检查服务器重启数据提交是否成功,并使用另一个Ajax调用1重新检查服务器是否正在重启以及数据是否已更新

我目前有以下两个ajax代码

Ajax调用1

 $.ajax({
           // dataType : 'jsonp',
            //jsonp : 'js',
            url: "some.json",
            beforeSend : function(jqXHR, settings) {
                console.info('in beforeSend');
                console.log(jqXHR, settings);
            },
            error : function(jqXHR, textStatus, errorThrown) {
                alert(" 500 top data still loading"+ jqXHR +  " : " + textStatus +  " : " + errorThrown);
                console.info('in error');
                console.log(jqXHR, textStatus, errorThrown);
            },
            complete : function(jqXHR, textStatus) {
             alert(" complete "+ jqXHR +  " : " + textStatus);
                console.info('in complete');
                console.log(jqXHR, textStatus);
            },
            success: function(data, textStatus, jqXHR){
            alert(" success "+ jqXHR +  " : " + textStatus);
                console.info('in success');
                console.log(data, textStatus, jqXHR);
            }
        }); 
Ajax调用2

 $(function () {
    $("#save").click(function () {

        $.ajax({
            type: "POST",
            url: "some.json",
            data: json_data,
            contentType: 'application/json',
            success: function (data, textStatus, xhr) {
                console.log(arguments);
                console.log(xhr.status);
                alert("Your changes are being submitted: " + textStatus + " : " + xhr.status);
                $('#myModal').modal('hide');
                /*                   
        This gives a messagthat  the server is restarting iina modal window and waits for 30sec
        */
                $('#myModal-loading').modal('show');

/***  Re check bit by Ryan ***/
var restartCheck = window.setInterval(
$.ajax({
    // dataType : 'jsonp',
    //jsonp : 'js',
    url: "../../../../../rest/configuration",
    beforeSend: function (jqXHR, settings) {
        console.info('in beforeSend');
        console.log(jqXHR, settings);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert(" 500 top data still loading " + jqXHR + " : " + textStatus + " : " + errorThrown);
        console.info('in error');
        console.log(jqXHR, textStatus, errorThrown);

    },
    complete: function (jqXHR, textStatus) {
        alert(" complete " + jqXHR + " : " + textStatus);
        console.info('in complete');
        console.log(jqXHR, textStatus);
    },
    success: function (data, textStatus, jqXHR) {
        window.clearInterval(restartCheck);
        alert(" success " + jqXHR + " : " + textStatus);
        console.info('in success');
        console.log(data, textStatus, jqXHR);
    }
}), 30000); //This will call the ajax function every 3 seconds until the clearInterval function is called in the success callback.
/*** recheck bit **/

                setTimeout(function () {
                    location.reload(true);
                }, 30000);

                $('<div id="loading">Loading...</div>').insertBefore('#myform-wiz');

            },

            error: function (jqXHR, textStatus, errorThrown) {
                alert(jqXHR.responseText + " - " + errorThrown + " : " + jqXHR.status);

            }
        });

    });
});



});
$(函数(){
$(“#保存”)。单击(函数(){
$.ajax({
类型:“POST”,
url:“some.json”,
数据:json_数据,
contentType:'应用程序/json',
成功:函数(数据、文本状态、xhr){
log(参数);
控制台日志(xhr.status);
警报(“您的更改正在提交:“+textStatus+”:“+xhr.status”);
$('#myModal').modal('hide');
/*                   
这会发出消息,表明服务器正在重新启动iina模式窗口并等待30秒
*/
$('#myModal loading').modal('show');
/***重新检查Ryan的钻头***/
var restartCheck=window.setInterval(
$.ajax({
//数据类型:“jsonp”,
//jsonp:'js',
url:“../../../../../rest/configuration”,
发送前:函数(jqXHR,设置){
console.info('in beforeSend');
console.log(jqXHR,设置);
},
错误:函数(jqXHR、textStatus、errorshown){
警报(“500个顶级数据仍在加载”+jqXHR+”:“+textStatus+”:“+ERRORSHORN”);
console.info('in error');
log(jqXHR、textStatus、errorshown);
},
完成:函数(jqXHR,textStatus){
警报(“完成”+jqXHR+:“+textStatus);
控制台信息(“完整”);
console.log(jqXHR,textStatus);
},
成功:函数(数据、文本状态、jqXHR){
清除间隔(重新启动检查);
警报(“成功”+jqXHR+:“+textStatus);
console.info('in success');
日志(数据、文本状态、jqXHR);
}
}),30000);//这将每隔3秒调用一次ajax函数,直到在成功回调中调用clearInterval函数为止。
/***复查钻头**/
setTimeout(函数(){
位置。重新加载(true);
}, 30000);
$('Loading…')。insertBefore('myformwiz');
},
错误:函数(jqXHR、textStatus、errorshown){
警报(jqXHR.responseText+“-”+errorshown+”:“+jqXHR.status);
}
});
});
});
});

如果服务器发出500条错误消息以检查服务器是否重新启动,并在重定向回更新页面之前重新检查200次是否成功,是否可以在
Ajax call 2
中的success内连续重新检查

您可以使用setInterval。不要忘记在成功回调中清除它

var restartCheck = window.setInterval(    
$.ajax({
           // dataType : 'jsonp',
            //jsonp : 'js',
            url: "some.json",
            beforeSend : function(jqXHR, settings) {
                console.info('in beforeSend');
                console.log(jqXHR, settings);
            },
            error : function(jqXHR, textStatus, errorThrown) {
                alert(" 500 top data still loading"+ jqXHR +  " : " + textStatus +  " : " + errorThrown);
                console.info('in error');
                console.log(jqXHR, textStatus, errorThrown);

            },
            complete : function(jqXHR, textStatus) {
                alert(" complete "+ jqXHR +  " : " + textStatus);
                console.info('in complete');
                console.log(jqXHR, textStatus);
            },
            success: function(data, textStatus, jqXHR){
                window.clearInterval(restartCheck);
                alert(" success "+ jqXHR +  " : " + textStatus);
                console.info('in success');
                console.log(data, textStatus, jqXHR);
            }
        })
, 3000);  //This will call the ajax function every 3 seconds until the clearInterval function is called in the success callback.

我的想法是将您的
ajax
请求放入一个方法中,然后执行以下操作:


1。发送请求以保存数据并重新启动服务器

2.在此过程中,您需要验证数据是否在数据库中重复

3.如果存在错误,则该方法会反复执行,但由于在第2个步骤中执行了验证,因此数据不会双重保存,只有服务器重新启动


首先,我模拟了你的情况。我只是想知道,我不知道您使用的是哪种服务器语言(因为问题
标记
中没有指定它),但我将使用
PHP
来简化这一过程

以下示例说明了这一点:

用户在文本框中输入他的/她的姓名,然后当他/她单击“保存”按钮时,数据将发送到服务器,并且在
50秒之后,回调将返回到客户端。但是,如果输入名称是
oscar
,那么服务器将返回
500http
错误,您将看到代码如何再次执行,以再次尝试“重新启动”服务器(记住这是一个模拟)。否则一切都将返回
200http
OK

  • 请阅读代码中的所有注释,检查浏览器控制台,如果可以。。。试试看

index.php:这是主页面

<html>
<head>
<title>Simulation</title>
</head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  $('#btn').click(function() {
     save();
  });
});

function save() {

    $('#msg').text('Please wait while restarting the server...').show();
    $('#btn').hide();

    $.ajax({
        type: 'POST',
        url: 'process.php',
        data: $('form').serialize(),
        statusCode: {
            500: function() { 

                console.log('500 HTTP error present, try again...');

                /* Invoke your method again to try restarting the server. 
                 * To avoid double save of 'name' variable please 
                 * check the first comments at 'process.php' file.
                 */
                $('#msg').text('Re-trying to restart the server...');

                /* While waiting check the browser console and look that 
                 * the save method is getting invoked again and again until 
                 * you change the name from 'oscar' to another.
                 */
                save();
            },
            200: function() {
                $('#msg').text('Server restarted!').fadeOut('slow');
                $('#btn').fadeIn();
            }
        }
    });

};
</script>
<body>
<span id="msg"></span>
<br/>
<form>
Name: <input type="text" name="name" id="name"/><br/>
<input type="button" name="btn" id="btn" value="Save"/>
</form>
</body>
</html>


希望这能有所帮助:-)

我是在成功后的第二次ajax调用中插入它,还是将它们分开,就像我最初做的那样,并修改第一次ajax调用1?无论哪种方式。我可能会将其封装在自己的函数中,并从“ajax2”函数的成功回调中调用它,只是为了保持干净。或者你可以把整个东西都嵌入其中,但这很难阅读。我在“AJAX2”的成功中添加了你的代码,你能检查一下这是否正确吗?它似乎没有等待,我认为旧的200改变为500(重新启动)。,。初始成功时的进程(200)-->(等待30秒等待(500)-或重新检查-再等待30秒等待200次重新检查。必须检查并重新检查所有这些服务器响应值,直到完成为止。您如何重新检查重新启动()定期地,如果它最终从500更改为200,请记住服务器重新启动大约需要40到50秒?而且,重新启动是一个2步
<?php
if(isset($_POST['name'])){

  $name = $_POST['name'];

  /* TODO: In this case and at this point, you need to save the 
   * name into DB but only if it doesn't exist because if 500 error
   * is present, then the request have to be validated again to 
   * just restart the server (maybe doing some if/else to evaluate) and 
   * don't make a double save.
   */

  /* TODO: restart the server... 
   * I will simulate the long wait for the server to respond (50s)
   * using sleep before sending back the name variable to client side.
   *
   * But!
   * I will do a tricky thing at this point. If the name is 'oscar' then
   * I will produce a 500 HTTP error to see what happens at client side...
   */

   /* Wait first 27s */
   sleep(27);

   /* If $name is 'oscar' then return 500 error */
   if($name == 'oscar') {
    throw new Exception('This is a generated 500 HTTP server error.');
   }

   /* If $name != 'oscar' then wait 23s to simulate 
    * the long time for restarting server...
    */
    sleep(23);

    flush();

    /* Retun $name in the callback */
    echo $name;  
}
?>