javascript - 如何在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 循环的情况下直接访问它的值。
解决方案
推荐阅读
- regex - 基于 IP 地址 RegEx 的反应式表单有效性
- python - xarray CFTimeIndex.to_datetimeindex out of bounds nanosecond timestamp
- php - Laravel Broadcast - Disconnect previously authorized user
- python - 如何解决错误:ModuleNotFoundError: No module named 'jupyterhub'
- python - Gravity strength and jump height somehow dependant on framerate - Pygame
- c++ - 如何使用 C++ 将字符串中的字符转换为整数变量
- primefaces - Primefaces数据表选择大数据集慢
- python - Tkinter:无法用小部件填充整个框架
- php - 当我在 com 和其他小词上搜索时,MongoDb 全文搜索会占用内存
- flutter - Flutter - 事件/时间线预约预约布局问题