drci47425 2018-11-13 09:16 采纳率: 100%
浏览 43

如何避免将PHP结果包装到另一个数组中?

The following is the php code:

<?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;
 }
 ?>

On the scriptside, it was called like this:

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)
  })
}

Now, as far as I understand php, it creates an array with the names of the columns being the keys to the respective values. However, the array that is returned to the front-end seems to be multidimensional, see the following output:

[{"name":"----","vorname":"-----","email":"---.---@example.de"}]

Why is that? And is there any way around it? This way, I always have to address the numerical index "0" first, and then in the second index write out the respective associative key. While this isn't a major issue, it feels rather "unclean", since this is neither necessary nor was it intended.

</div>
  • 写回答

1条回答 默认 最新

  • duanmei1885 2018-11-13 09:32
    关注

    According to 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.

    and

    As long as the response from the server is written in JSON format, you can parse the string into a JavaScript object.

    so try changing your response format to 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)    
        })
    }
    

    Assuming the response is a valid JSON string of course.

    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法