简体   繁体   English

Ajax,为什么setInterval函数不起作用?

[英]Ajax, why the setInterval function doesn't work?

I just have a json page in localhost and I save the data of this page in a file , I need to save this page every 5 seconds, so I developed this code in ajax , using a page in php with an exec command,I used a setinterval function for the update but my code execute the function getRequest only one time. 我在localhost中只有一个json页面,并将该页面的数据保存在一个文件中,我需要每5秒保存一次此页面,因此我在ajax中开发了此代码,并在php中使用exec命令使用了该页面,一个setinterval函数用于更新,但是我的代码仅执行一次getRequest函数。 Here the html: 这里的HTML:

<script type="text/javascript">
    // handles the click event for link 1, sends the query
  function getOutput() {
    setInterval(function(){
 getRequest(
      'prova1.php', // URL for the PHP file
       drawOutput,  // handle successful request
       drawError    // handle error
  );
  return false;
  },3000);
}  
// handles drawing an error message
function drawError() {
    var container = document.getElementById('output');
    container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
    var container = document.getElementById('output');
    container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
    var req = false;
    try{
        // most browsers
        req = new XMLHttpRequest();
    } catch (e){
        // IE
        try{
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            // try an older version
            try{
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                return false;
            }
        }
    }
    if (!req) return false;
    if (typeof success != 'function') success = function () {};
    if (typeof error!= 'function') error = function () {};
    req.onreadystatechange = function(){
        if(req.readyState == 4) {
            return req.status === 200 ? 
                success(req.responseText) : error(req.status);
        }
    }
    req.open("GET", url, true);
    req.send(null);
    return req;
}
</script>

And here the php page: 而这里的PHP页面:

<?php
  exec(" wget http://127.0.0.1:8082/Canvases/Fe0_Cbc1_Calibration/root.json -O provami3.json", $output);
  echo 'ok';
?>

I'm new to php , javascript ajax etc and Im learning it a piece at time, I know that maybe there is an easy way for it using jQuery but for now I'm learning Ajax, so I'd like have an advice for doing it with Ajax. 我是php,javascript ajax等的新手,我一次学习了一部分,我知道使用jQuery可能有一种简单的方法,但是现在我正在学习Ajax,所以我想对用Ajax来做。 Thank you all. 谢谢你们。

Do you have called getOutput() function?I don't see it... 你调用过getOutput()函数吗?我没看到...

Working example with your code here: http://jsfiddle.net/v9xf1jsw/2/ 在此处使用代码的示例: http : //jsfiddle.net/v9xf1jsw/2/

I've only added this at the end: 我只在最后添加了:

getOutput();

Edit: Working example with getOutput call into a link: http://jsfiddle.net/v9xf1jsw/8/ 编辑:使用getOutput调用链接的工作示例: http : //jsfiddle.net/v9xf1jsw/8/

The JS is fine, see example here counting the loops https://jsfiddle.net/tk9kfdna/1/ JS很好,请参见此处的示例计数循环https://jsfiddle.net/tk9kfdna/1/

<div id="output"></div>
<div id="log"></div>
<script type="text/javascript">
// handles the click event for link 1, sends the query

var times=0;

function getOutput() {
  setInterval(function(){
 getRequest(
  'prova1.php', // URL for the PHP file
   drawOutput,  // handle successful request
   drawError    // handle error
  );
  return false;
  },3000);
}  
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
function getRequest(url, success, error) {

times++;

var req = false;
try{
    // most browsers
    req = new XMLHttpRequest();
} catch (e){
    // IE
    try{
        req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
        // try an older version
        try{
            req = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(e) {
            return false;
        }
    }
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
    if(req.readyState == 4) {
        return req.status === 200 ? 
            success(req.responseText) : error(req.status);
    }
}
req.open("GET", url, true);
req.send(null);

var log = document.getElementById('log');
log.innerHTML = 'Loop:'+times;

return req;


}

getOutput();
</script>

Assuming here your calling getOutput() somewhere as that was not included in your original question if not it may just be that. 假设您在此处调用getOutput()的原因是,您的原始问题中没有包含该内容,如果不是这样的话。 Otherwise what may be happening is a response from prova1.php is never being received and so the script appears like it's not working. 否则可能发生的是从未收到来自prova1.php的响应,因此该脚本似乎无法正常工作。 The default timeout for XMLHttpRequest request is 0 meaning it will run forever unless you specify the timeout. XMLHttpRequest请求的默认超时为0,这意味着它将永久运行,除非您指定超时。

Try setting a shorter timeout by adding 尝试通过添加一个更短的超时

req.timeout = 2000; // two seconds

Likely there is an issue with prova1.php? prova1.php可能有问题? does prova1.php run ok when your try it standalone. 当您独立尝试时,prova1.php是否可以正常运行。

1) Return false at the end of the setInterval method, I don't believe this is necessary. 1)在setInterval方法的末尾返回false,我认为这不是必需的。

2) Use a global variable to store the setInterval, (this will also give you the option to cancel the setInterval). 2)使用全局变量存储setInterval,(这还将为您提供取消setInterval的选项)。

var myInterval;
function getOutput() {
    myInterval = setInterval(function(){
 getRequest(
      'prova1.php', // URL for the PHP file
       drawOutput,  // handle successful request
       drawError    // handle error
  );
  },3000);
}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM