通过AJAX从JSON编码获取数组

时间:2019-11-12 03:40:04

标签: javascript arrays json ajax

我正在尝试使用AJAX请求将我在一个单独文件中拥有的4个JSON数组转换为我的主文件。出于某种原因,我似乎无法将数组放入变量中并将其显示在控制台日志中。 这是JSON文件的结果:

[[5,10,10.99,10.99,13,5,14.31,1,1,5,5,5,1,5,3,3,5,5,1,5,10.32,10.32,5,8,5,10,5,5,19,5,7.36,7.36,5,12.2,12.2,2.2,2.2,23.3,5,10.87,6.87,6.87,5,5,10,10,10,10,5,5,5,5,5,0,5,5],

[8,12.5,12.5,12.53,12.53,8,10.11,1,1,8,8,8,1,8,3,3,8,8,1,8,12.83,32.32,8,8,8,10,8.31,8,10,8,18.2,18.2,8,10.3,10.3,2.29,2.29,12.3,8,8.23,2.23,2.23,8,8,10,10,10,20,5,5,5,5,8,0,8,2],

[6,8.86,8.86,8.87,8.87,6,8.33,1,2,6,2,3,1,6,3,8,6,6,1,6,8.32,7.32,6,8,6,10,3.31,6,12,6,12.3,12.3,6,11.1,11.1,4.09,4.09,33.1,6,5.16,12.16,2.16,6,6,10,20,30,30,30,30,5,0,6,0,6,5],

[19,31.36,32.36,32.4,34.4,19,32.76,3,4,19,15,16,3,19,9,14,19,19,3,19,31.47,49.96,19,24,19,30,16.62,19,41,19,37.86,37.86,19,33.6,33.6,8.6,8.6,68.7,19,24.26,21.26,11.26,19,19,30,40,50,60,40,40,15,10,19,0,19,12]]

这是我尝试将其放入主页的方法:

function callback(response) {
      var array1 = response[0];
      var array2 = response[1];
      var array3 = response[2];
      var array4 = response[3];
      console.log(array1);
}

$.ajax({
  url: 'loadchart.php',
  success: callback
});

我试图只获取所有array1的结果只是一个括号:

[

loadchart.php中的代码:

<?php 

  session_start();

  if(!isset($_SESSION['usersId']))
  {
    header("Location: ../index.php");
    exit();
  }
  else
  {
    include_once 'includes/dbh.inc.php';
  }

  $id = $_SESSION['userId']; 
  $dBname = "infosensor";
  $conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBname);

  $sql = "SELECT sensor1, sensor2, sensor3 FROM `$id`;";

  $result = mysqli_query($conn, $sql);
  $jsonsensor1 = array();
  $jsonsensor2 = array();
  $jsonsensor3 = array();
  $jsonsensorsum = array();
  if (mysqli_num_rows($result) > 0)
  {
    while ($row = mysqli_fetch_assoc($result))
    {
      $jsonsensor1[] = intval($row['sensor1'] * ($p = pow(10, 2))) / $p;
      $jsonsensor2[] = intval($row['sensor2'] * ($p = pow(10, 2))) / $p;
      $jsonsensor3[] = intval($row['sensor3'] * ($p = pow(10, 2))) / $p;
      $jsonsensorsum[] = intval(($row['sensor1'] + $row['sensor2'] + $row['sensor3']) * ($p = pow(10, 2))) / $p;
      $data = [$jsonsensor1,$jsonsensor2,$jsonsensor3,$jsonsensorsum];
    } 
  }

  echo json_encode($data);

2 个答案:

答案 0 :(得分:1)

将dataType添加为json:

$.ajax({
      url: 'loadchart.php',
      dataType:"json",
      success: callback
    });

答案 1 :(得分:1)

只需做一件事,用户JSON.parse即可解析您的json数组 就像我在您的工作中所做的一样

function callback(response) {
  var res= JSON.parse(response);
  var array1 = res[0];
  var array2 = res[1];
  var array3 = res[2];
  var array4 = res[3];
  console.log(array1);
}