0

如果没有达到预期的结果,是否有任何方法可以进行 ajax 调用,提取一个值并每隔 X 秒(或根据用户请求)不断重复,直到达到预期的结果?

调用的响应以 json 序列化数组的形式呈现。我希望 ajax 调用不断重复,直到$status_codeis1或 response == "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
4

3 回答 3

1

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

现在,不再像当前那样将结果返回为 html,而是将其返回为 JSON,以便您可以轻松地在客户端对其进行评估。elseif{...}在您的 php 代码中包含必要的 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(){or else{。这可能会为您尝试评估您的代码的 javascript 编译器节省一些麻烦。

例子:

return{
   object
}
// returns the object

应该相同,但不一样:

return // comiler will add a ; after your return, thus your object won't be returned
{
   object
}
于 2012-04-18T20:34:31.230 回答
1

是的,您可以递归地执行此操作。

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();  
于 2012-04-18T20:40:49.947 回答
1

不知道问题出在哪里,但如果我理解正确的话,你就足够了:

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.
        }
    });

并且仅通过调用来使用它......它的结果不会达到 - 它使用递增队列进行递归调用,第一次调用不需要任何参数。

希望这正是您所需要的。

于 2012-04-19T06:40:21.787 回答