目的の結果が満たされない場合に、ajax呼び出しで値を抽出し、目的の結果に達するまでX秒ごとに(またはユーザーの要求に応じて)繰り返し続ける方法はありますか?
呼び出しの応答は、jsonでシリアル化された配列として表示されます。$status_code
ajax呼び出しは、 is1
または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