简体   繁体   中英

Reload variables every 10 seconds

Okay here's the problem. I want to have 6 realtime variables in php (now they are like Divs). The method I use works fine but it's awful (I know). I need better solution.

Now I load 6 diffrent files like this:

<script>
function loadText() {
$.ajax({
    url: ("variable1.php"),
    cache: false,
    success: function(data) {
        $("#variable1").html(data);
    }
});
} setInterval(loadText, 60000);
</script>

<div id="variable1"></div>

What should I do? Thanks.

Are you going to want to do a setInterval() ?

setInterval(function(){loadText();}, 10000);

Or, if you want it to run only after successfully completing the call, you can set it up in your .ajax().success() callback:

function loadText(){
    var text = $.ajax({
        type: "POST",
        url: "variable1.php",
        async: false
    }).success(function(){
        setTimeout(function(){loadText();}, 10000);
    }).responseText;

    $('#variable1').html(text);
}

Or use .ajax().complete() if you want it to run regardless of result:

function loadText(){
    var text = $.ajax({
        type: "POST",
        url: "variable1.php",
        async: false
    }).complete(function(){
        setTimeout(function(){loadText();}, 10000);
    }).responseText;

    $('#variable1').html(text);
}

Here is a demonstration of the two. Note, the success works only once because jsfiddle is returning a 404 error on the ajax call.

http://jsfiddle.net/YXMPn/

您始终可以设置一个要运行的函数,但是经常需要它具有此功能……这是一种简短得多的方法……如果这就是您的意思……

$("#variable1").load("variable1.php");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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