doushi8187 2015-11-10 09:49
浏览 35
已采纳

jquery每2秒后从php页面获取数据

I am get data from php page after every 2 secounds the data is very large when i call it once then the data comes but when i place my code in setinterval function then the data in console is not showing I place this code in setinterval function because after every 2 sec i need fresh data any idea plz share

var data_array = '';

     setInterval(function () {
        $.ajax({
            url:"./phponline.php",
            async:false,
            success:function(res)
            {
                data_array = res;
            },
            error:function(errorMsg)
            {

            }
        }); 
         }, 5000);
 console.log(data_array); 
  • 写回答

4条回答 默认 最新

  • dqly83915 2015-11-10 10:13
    关注

    There's a couple of issues you have here, the main one being that you're trying to make a synchronous ajax call, and that's been deprecated. You need to handle it being an asynchronous call instead...

    Put the code that you want to run every time you get new data into a function and call that function in the success callback

    var data_array = '';  // this is a global variable
    
    function getNewData() {
        $.ajax({
            url: "./phponline.php",
        })
        .done(function(res) {
            data_array = res;  // the global variable is updated here and accessible elsewhere
            getNewDataSuccess();
        })
        .fail(function() {
            // handle errors here
        })
        .always(function() {
            // we've completed the call and updated the global variable, so set a timeout to make the call again
            setTimeout(getNewData, 2000);
        });
    }
    
    function getNewDataSuccess() {
        console.log(data_array); 
    }
    
    getNewData();
    

    As I explained in the comments, using setInterval with an ajax call is a bad idea as you could end up overlapping calls if they take longer than the interval. This method makes a call, waits for the result and then uses setTimeout to make the next call instead. This way you can never make an ajax call until 2 seconds after the last one was completed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程