Auto refresh included PHP file inside a DIV

后端 未结 3 784

I have a file called messages.php which runs SQL queries to a database and displays results in a $res variable

My menu.php page I used

i         


        
相关标签:
3条回答
  • 2021-01-20 21:27

    This requires the jQuery library. It could be done in pure JS, but if you're a JS beginner I recommend using jQuery.

    function reload_messages(){
        $.get("messages.php", function(data) {
            $("#id").html(data);
        });
    }
    

    You will then need to call reload_messages, for example:

    <a href="javascript:reload_messages();">reload messages</a>
    

    If you want to expand on the .get method, check out this page: https://api.jquery.com/jQuery.get/

    0 讨论(0)
  • 2021-01-20 21:40

    If you want it to refresh on an interval, you can make use of setInterval

    setInterval( refreshMessages, 1000 );
    

    1000 is 1000 milliseconds, so 1 second, change this to how you like.

    So every 1 second it triggers the function refreshMessages:

    function refreshMessages()
    {
        $.ajax({
            url: 'messages.php',
            type: 'GET',
            dataType: 'html'
        })
        .done(function( data ) {
            $('#msgs').html( data ); // data came back ok, so display it
        })
        .fail(function() {
            $('#msgs').prepend('Error retrieving new messages..'); // there was an error, so display an error
        });
    }
    
    0 讨论(0)
  • 2021-01-20 21:50

    First Remove include 'messages.php'; Then remove echo $res; from div and put it in the last line of messages.php

    and try the following code after including the jquery file

    <script>
    jQuery().ready(function(){
        setInterval("getResult()",1000);
    });
    function getResult(){   
        jQuery.post("messages.php",function( data ) {
            jQuery("#msgs").html(data);
        });
    }
    </script>
    <div id="msgs">
    </div>
    
    0 讨论(0)
提交回复
热议问题