以下是php代码:
<?php
session_start();
if(isset($_SESSION["loggedUser"])) {
generateAndProvideData($_SESSION["loggedUser"]);
} else {
//error handling
}
function generateAndProvideData($loggedUser) {
$connection = establishConnectionToDatabase();
$UserData = retrieveUserData($connection, $loggedUser);
echo json_encode($UserData);
}
function retrieveUserData($connection, $loggedUser) {
return $connection->query("
SELECT name, vorname, email
FROM benutzer
WHERE id = '".$loggedUser."'
")->fetchAll(PDO::FETCH_ASSOC);
}
function establishConnectionToDatabase() {
try {
$connection = new PDO('mysql:host=localhost;dbname=------------','------','-----');
} catch(PDOException $e) {
echo $e->getMessage();
}
return $connection;
}
?>
在脚本方面,它的名称如下:
function populateUserData() {
$.post('../include/getUserDataForBenutzerprofil.php', {
//nothing to transmit
}).then((data) => {
data = JSON.parse(data)
console.log("data from getUserDataForBenutzerprofil.php is ", data)
//$('#name').val(data.name)
})
}
现在,据我所知,php创建了一个数组,其列名是各个值的键。 但是,返回到前端的数组似乎是多维的,请参见以下输出:
[{“ name”:“ ----”,“ vorname”:“ -----”,“ email”:“ ---.--- @ example.de”}]]
那是为什么?周围有什么办法吗? 这样,我总是必须首先处理数字索引“ 0”,然后在第二个索引中写出相应的关联关键字。尽管这不是一个主要问题,但感觉很“不洁”,因为这既没有必要,也不是故意的。
答案 0 :(得分:0)
根据https://www.w3schools.com/js/js_json_parse.asp
When using the JSON.parse() on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object.
和
As long as the response from the server is written in JSON format, you can parse the string into a JavaScript object.
因此请尝试将您的回复格式更改为json
。
function populateUserData() {
$.ajax({
type: "POST",
url: "../include/getUserDataForBenutzerprofil.php",
// data: {},
dataType: "json" //<-- this
}).then((data) => {
data = JSON.parse(data)
console.log("data from getUserDataForBenutzerprofil.php is ", data)
})
}
假定响应当然是有效的JSON字符串。