JavaScript自动检查问题

时间:2015-08-21 13:36:59

标签: javascript php jquery

我正在尝试检查是否已使用jQuery.get()发布了我的软件的新版本;通过调用PHP脚本然后获取它返回的内容并离开它。这是我的代码:

JavaScript代码:

var old_count = 0;
$.get("api/build/update-check.php", function(data) {
    old_count = data;
});

window.setInterval(function() {
    $.get("api/build/update-check.php", function(data) {
        var count = old_count;
        if(old_count < count)
            console.warn("There is a new build available!");
        console.log("Old Count: " + old_count);
        console.log("New Count: " + count);
        old_count = count;
    });
    console.info("Checked for new builds successfully!");
}, 5000);

PHP脚本:

<?php
$fi = new FilesystemIterator("../../download/builds/", FilesystemIterator::SKIP_DOTS);
$count = iterator_count($fi) - 1; //Subtract the .htaccess file

echo $count;

它将完美地运行一切,并且它将重新运行该方法,就像它应该很好,但是,当它重新运行脚本时,它不会更改变量。我知道PHP脚本运行正常,因为我测试过它。我认为问题在于它会在一段时间内获得检查脚本,然后在间隔期间保留该脚本。有没有办法让它每次都调用PHP脚本或者我需要更改什么才能使它按照我的意图运行?

2 个答案:

答案 0 :(得分:3)

我认为存在问题

var count = old_count;
if(old_count < count)

它们100%相等,这些值如何不同?

我认为你的意思是

var count = data;

在这个地方;)

var old_count = 0;
$.get("api/build/update-check.php", function(data) {
    old_count = data;
});

window.setInterval(function() {
    $.get("api/build/update-check.php", function(data) {
        // count = data instead of old_count. You assign old_count = count later
        var count = data;
        if(old_count < count)
            console.warn("There is a new build available!");
        console.log("Old Count: " + old_count);
        console.log("New Count: " + count);
        old_count = count;
    });
    console.info("Checked for new builds successfully!");
}, 5000);

答案 1 :(得分:0)

您可以通过请求带有如下随机查询字符串的PHP页面来阻止缓存:

window.setInterval(function() {
    $.get("api/build/update-check.php?"+Math.random(), function(data) {
        // ...
    });
    console.info("Checked for new builds successfully!");
}, 5000);