dongmi5015 2016-05-30 13:04
浏览 26
已采纳

首次使用AJAX从PHP获取数据

So i simply use this updateData function to get values from my php file it works after the first interval, but I would like to get first data after the page loads so I've tried doing var

var dataset=[];
updateData();

Before the intervals starts but dataset is still not updated immidiately I get empty array []

function updateData(){
    $.ajax({
            type: 'POST',
            url: 'parser.php',         
            dataType: 'json',
            cache: false,
            success: function(result) {
                dataset = result;
            },
    });

}
<?php 
    $datasetJSON = array();

    for($i=0;$i<7;$i++){
        $datasetJSON[] = rand(1,1000);
    }
    echo json_encode($datasetJSON);
?>
  • 写回答

3条回答 默认 最新

  • douzouchang7448 2016-05-30 13:16
    关注

    I think your problem is understanding that AJAX is not synced!

    That means your code will keep running and not wait for the AJAX call to return. You could think of AJAX calls as threads that will run seperately of your main thread.

      var dataset=[];
      updateData();
      console.log(dataset); // will execute immediately!
      function updateData(){
          $.ajax({
                  type: 'POST',
                  url: 'parser.php',
                  dataType: 'json',
                  cache: false,
                  success: function(result) {
                      dataset = result;
                      console.log(dataset); // now it's updated
                  },
          });
      }
    

    You could call AJAX synced:

      var dataset=[];
      updateData();
      console.log(dataset); // now it's updated
      function updateData(){
          $.ajax({
                  type: 'POST',
                  url: 'parser.php',
                  dataType: 'json',
                  cache: false,
                  async: false, // <-- This will sync the AJAX call (and freeze the browser)
                  success: function(result) {
                      dataset = result;
                      console.log(dataset); // now it's updated
                  },
          });
      }
    

    However, it defeats the purpose of AJAX. You should learn how the deal with callback functions.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器