简体   繁体   中英

how do I “ajaxify” my php code?

I have divs that I want to display at specific times throughout the day. I have it working in PHP, but it requires refreshing the browser manually. I would like my script to automatically load the right div when the time is right.

Am I on the right track? Perhaps there is a jquery plugin for this sort of thing that would handle the refreshing?

Any help is greatly appreciated... Thanks!

<?php

$time = date("H\:i");

if (($time > "16:59") && ($time < "18:59")) {
    echo "<div>1</div>";
}

elseif (($time > "18:59") && ($time < "20:59")) {
    echo "<div>2</div>"; 
}

elseif (($time > "20:59") && ($time < "22:59")) {
    echo "<div>3</div>";    
}

 else {
    echo "<div id='out'><p>Outside the specified point in time.</p></div>";
}

?>

You won't need a jquery plugin to handle refreshing, you can just create a timer which checks every few minutes/seconds

@jasie was right to mention timers. He mentioned jquery timer, but you can just as well use regular javascript timers, like this (you tagged jquery, so I'll use jquery):

var timer = setInterval(function(){
    var hour = (new Date()).getHours();

    if (hour >= 17 && hour < 19) {
        var $div = $('<div>1</div>');
    } else if (hour >= 19 && hour < 21) {
        var $div = $('<div>2</div>');
    } else if (hour >= 21 && hour < 23) {
        var $div = $('<div>3</div>');
    } else {
        var $div = $("<div id='out'><p>Outside the specified point in time.</p></div>");
    }
    $div.appendTo('body');
}, 2000); // checking every 2 seconds.

That should do the trick

I would use JQuery timer to poll every so often; when the time is right, use a $.load() to load in new information into the div on the page. You should do the time checks in Javascript, as you've done, so that you're not constantly transferring needless data between client and server.

Your backend should return a specific bit of html you want to display.

Your front-end should just be polling one specific url on the backend that returns this information.

(There are other ways to do it but this is my opinion)

As a start, using jQuery's AJAX call and a simple js timer. If page has one div with ID of "showithere", this willre-load your PHP page every 10 minutes:

<head>
<script>
​function fn () {
  alert ('now');
  $("#showithere").load ("http://jsbin.com/help/");
}
</script>
</head>

<body onLoad="setTimeout (fn, 600000);" >

​​​​​​​​​​​​​​​

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