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 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端