进行 ajax 调用,如果不是所需的结果,则提取一个值,然后继续重复,直到达到所需的结果


Make ajax call, if not desired result, extract a value, then keep repeating until desired result is reached

ajax 调用有什么方法,如果没有满足所需的结果,提取一个值并每 X 秒(或应用户请求)不断重复一次,直到达到所需的结果?

调用的响应显示为 json 序列化数组。我希望 ajax 调用不断重复,直到$status_code 1或响应 == "error_bad_api_call" .

剪断的旧代码

更新:(答案)

我们将调用的PHP脚本(10%的机会提供预期结果):

<?php
$retArr = array();
$rand = rand(1, 1000);
if($rand < 100)
{
    $retArr["status_code"] = 1;
    echo json_encode($retArr);
}
else
{
    $retArr["status_code"] = 0;
    echo json_encode($retArr);
}
?>

javascript + html

<html>
<head>
<script src="include/jquery-1.7.2.min.js"></script>
<script src="include/jquery.json-2.3.min.js"></script>
<script type="text/javascript">
//Clean all elements on button click
function dosubmitClean(tries)
{
    document.getElementById("resultsHere").innerHTML="";
    document.getElementById("temp").innerHTML="";
    document.getElementById("tries").innerHTML="";
    dosubmit(tries); //Do actual work
}
function dosubmit(tries)
{
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else{// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            var resp = xmlhttp.responseText; //Get response
            document.getElementById("temp").innerHTML+="resp: "+xmlhttp.responseText+"<br/>"; //Show in event log
            var status_code = $.evalJSON(resp).status_code; //Get status code
            document.getElementById("temp").innerHTML+="status_code: "+status_code+"<br/>"; //Show in event log
            document.getElementById("temp").innerHTML+="Checking status code <br/>"; //Show in event log
            if(status_code == "1"){
                document.getElementById("resultsHere").innerHTML+="status_code: is one <br/>"; //Show final result
                document.getElementById("temp").innerHTML+="status_code: is one <br/>"; //Show in event log
                document.getElementById("tries").innerHTML="Amount of tries: "+tries+"<br/><br/>Event log:<br/>"; //Show amount of tries
            }
            else{
                document.getElementById("temp").innerHTML+="status_code: is NOT one <br/>"; //Show in event log
                tries++; //Tries + 1
                dosubmit(tries,"someval"); //Loop
            }
            document.getElementById("temp").innerHTML+="Done checking status code <br/><br/>"; //Show in event log
        }
    }
    xmlhttp.open("GET","json_repeat_php.php",true);
    xmlhttp.send();
}
</script>
</head>
<body>
<input type="submit" value="submit" id="postDataSubmit" onClick="dosubmitClean(<?php echo 1; ?>);return false;">
<div id="resultsHere"></div>
<div id="tries"></div>
<div id="temp"></div>
</body>
</html>

示例输出:

status_code: is one
Amount of tries: 2
Event log:
resp: {"status_code":0}
status_code: 0
Checking status code
status_code: is NOT one
Done checking status code
resp: {"status_code":1}
status_code: 1
Checking status code
status_code: is one
Done checking status code

这很容易。您已经有了回调函数,正在等待结果。

现在,

您不再像现在那样以 html 形式返回结果,而是将其作为 JSON 返回,这样您就可以在客户端轻松评估它。在 php 代码的elseif{...}中包含必要的 queueCodes。

这可能是这样的(注意,这只是伪代码!

your json = { success : 0|1 , resultarray [item,item] /* only if success=1 */ , someMoreInfo : <queueCode> }
if ( success ){
     // populate your html with the resulting items
}
else{
     //perhaps wait some time, then
     // call your ajax function again, with your queuecode as parameter
     dosubmit( json.someMoreInfo );
}

您的dosubmit函数将队列代码发送到您的服务器。

超时可能很有用,无论是在服务器还是客户端上,无论哪种方式都更适合您。

此外,您可能想看看 JSONP

旁注:在 PHP 的 elseif 分支中使用开关可能更合适。另外,尽量避免在javascript代码中的换行符上编写{,而是始终编写function(){else{。这可能会为您节省一些尝试评估代码的 JavaScript 编译器的麻烦。

例:

return{
   object
}
// returns the object

应该相同,但与以下不同:

return // comiler will add a ; after your return, thus your object won't be returned
{
   object
}

是的,你可以递归地做到这一点。

function send_request() 
{
    // perform ajax here and have a callback 
    // if value from callback indicates not successful call send_request() again
    send_request(); 
    // you may want to keep a count of how many times it fails, if it fails say, more than a set number of times then you can take the appropriate action 
}
send_request();  

不知道问题出在哪里,但如果我理解正确,你就可以做到:

function gather(queue) {
    data = $('form#foo').serialize();
    if (typeof queue != 'undefined') {
        data += '&queue=' + queue;
    } else {
        queue = 0;
    }
    $.ajax('/frontend_test.php', data, function(r) {
        var result = $.parseJSON(r);
        if (typeof result.status_code == 'undefined' || result.status_code != 1) {
            gather(++queue);
        } else {
            // Success, do whatever you need to.
        }
    });

并且只需调用即可使用它...它的结果不会达到 - 它进入递归调用与递增队列,第一次调用不需要任何参数。

希望这正是您所需要的。

相关文章: