开发者

AJAX: display a random line every minute

开发者 https://www.devze.com 2023-03-15 06:09 出处:网络
I have a PHP-script displaying random text: <?php $quotes = array( \'quote 1\', \'quote 2\', \'quote 3\',

I have a PHP-script displaying random text:

<?php

$quotes = array(
        'quote 1',
        'quote 2',
        'quote 3',
        'quote 4',
        'quote 5',
);

$i = array_rand($quotes);

header('Content-Type: text/plain; charset=utf-8');
print($quotes[$i]);

?>

How could I call it every minute to display a new quote (Russian text in UTF8 encoding) at my web page (which itself is an iframe app at Facebook)?

Do I need to use jQuery her开发者_开发百科e or is there a lighter solution, working in the usual browsers?

I don't have any AJAX experience yet.

UPDATE:

As suggested by Uku Loskit below, I've added the following snippet and it works well. Can anybody please show me how to fade the new quote in with fadeIn()?

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
        setTimeout( function() {
                $.get("/hint.php", function(data) {
                        $("#hint").html(data);
                });
        }, 5*60*1000 );
});
</script>

Thank you! Alex


use the setTimeout() method.

I'd say there's nothing heavy about using jQuery (especially the minified version) "just for AJAX", because it provides a cross-browser compatible solution and is much easier to program.

example:

function getNewQuotes() {
   $.get("random_quotes.php", function(data) {
       // set the response from random_quotes.php to this div
       $("#quotesDiv").html(data);
   }); 
}

// 60000 milliseconds = 60 seconds = 1 minute
var t=setTimeout("getNewQuotes()", 60000);

As for your question of mixing "non-JQuery and Javascript", there's no jQuery function for this that I know of, all-in-all jQuery is still Javascript and relying on jQuery specific code all the time isn't necessary, but would be only be useful for consistency.

Edit:

$(function() {
            setTimeout( function() {
                    $.get("/hint.php", function(data) {
                            // first hide, then insert contents
                            $("#hint").hide();
                            $("#hint").html(data);
                            // you can probably chain this together into one command as well
                            $("#hint").fadeIn("slow");

                    });
            }, 5*60*1000 );
});


You don't need jquery, but its easier like that. Just pick up from the manual Basic example of how to get it once:

$.ajax({
  url: "yourFileName.php",
  context: document.body,
  success: function(result){
    $('#someDiv').html('result');
  }
});

then add the javascript code to do this periodically. I'm sure you could find something nifty from the jquery thingymabob too :)

0

精彩评论

暂无评论...
验证码 换一张
取 消