以下代码进行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调用嵌入到我的大return数组中,以及如何不使用上面代码中看到的foreach循环直接访问其值。 。