首页 > 解决方案 > 如何在Javascript中处理包含数字和关联数组的数组?

问题描述

以下代码进行 AJAX 调用,然后将返回的字符串解析为 javascript 对象。

function parseJSONArrayAndOutputToConsole(jsonString) {
  var result = JSON.parse(jsonString)
  console.log("ajax-response from fetchDataFromDatabase " + result[4]);
}

function fetchDataFromDatabase() {
  $.ajax({
    type: "POST",
    url: 'Update.php',
    success: function(data) {
      //console.log("ajax-response from fetchDataFromDatabase " + data);
      parseJSONArrayAndOutputToConsole(data)

    },
    error: function(xhr, statusText, err) {
      console.log("ajax-error from fetchDataFromDatabase " + xhr.status);
    }
  })
}

setTimeout(function() {
  fetchDataFromDatabase();
}, 2000)

现在,从 AJAX 调用返回的数组包含 1 个字符串、1 个数值、2 个数值数组和最后一个关联数组。

当我尝试将关联数组输出到控制台时,我得到“[object Object]”。其他元素工作正常,只有关联数组不输出其值。关联数组的内容来自 AJAX 调用调用的 php 脚本内对数据库的调用。获取关联数组数据的 php 脚本如下所示:

//Lots of Code which doesn't matter for the issue at hand.
//The useCase I've been testing so far is where the user IS NOT
//an Admin.
if ($userRole == "admin") { //$testor  = 1;
  $result = $connection - > query("select id, name, vorname from benutzer order by name asc");
} else {
  //$testor =  0;
  $result = $connection - > query("
    SELECT benutzer.id, benutzer.name, benutzer.vorname FROM benutzer, benutzer_rollen WHERE benutzer.id = benutzer_rollen.benutzer AND benutzer_rollen.rolle != (
      select id from rolle where name = 'admin'
    ) ORDER BY benutzer.name ASC ");
  }
}
//The following else corresponds to an if which is not important here. 
// This else executes when the user is not logged in. 
//I didn't test the  
//behavior when the user is not logged in yet.
//Therefore, we can assume that any case I've tested so far, the data
//inside $result is fetched by the code inside the case where the user
//is logged in, but not an admin.
else {
  $result = $connection - > query("SELECT id, name, vorname FROM benutzer
    ORDER BY name ASC ");
  }

以这种方式创建的关联数组似乎可以工作,因为它后来用于设置一些 HTML 内容。看这里:

echo "<option value='leer' selected disabled hidden>Benutzer auswählen </option>";
foreach($result as $row) {

  //second ajax call to create contents in selectInput
  echo "<option ";
  if (isset($_SESSION["loggedUser"])) {
    if ($row["id"] == $_SESSION["loggedUser"]) {
      echo "selected";
    }
  }
  echo " >";
  echo $row["name"].
  ", ".$row["vorname"];
  echo "</option>";
}

我很难想象这个关联数组是如何从 ajax 调用嵌入到我的大返回数组中的,以及如何在不使用我们在上面代码中看到的 foreach 循环的情况下直接访问它的值。

标签: javascriptphpjqueryarraysajax

解决方案


推荐阅读