基于基于php文件的数据的实时ajax数据

问题描述 投票:1回答:1

这是我的index.html文件

$(document).ready(function() {

    $.ajax({
        url: 'ajax.php',
        type: 'GET',
        dataType: "json",

        beforeSend: function() 
        {

        },
        complete: function() 
        {

        },
        success: function(result) 
        {

        $("p").html(result.price);

        $("p").live("load", function() {
            $(this).html(result.price);
        });
        }
    });
});

这是ajax.php文件(我没有放json_decode,只是把val放到了测试用的那个上面)

{"price":"o"}

我想做的是,如果我转到ajax.php文件并将o更改为其他内容,我希望数据能够自动更新并显示在索引页面上而无需刷新,但是我似乎无法获取它起作用。我在做什么错?

php jquery ajax
1个回答
3
投票

客户端无法知道服务器上的某些内容已更改。因此,您可以通过setInterval函数使用定期的AJAX请求:

window.setInterval(function() {
    // Every 5 seconds send an AJAX request and update the price
    $.ajax({
        url: 'ajax.php',
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function(result) {
            $('p').html(result.price);
        }
    });
}, 5000);

另一种可能性是使用push AJAX

© www.soinside.com 2019 - 2024. All rights reserved.