javascript - 无法从 Key JSON MySQL PHP 获取值

标签 javascript php arrays json object

我正在使用 PHP 从 MySQL 数据库检索数据,并尝试使用 JSON.stringify 和 JSON.parse 创建对象。它工作正常,但我无法获取关联的键/值。只是整个对象。我把它分成几部分。这是 PHP 代码:

第一个 PHP 文件:

<?php
session_start();
include("web_db_operations.php");

if(isset($_POST['recipeId']) && isset($_SESSION['email'])){
    $recipeId = $_POST['recipeId'];
    $email = $_SESSION['email'];
}
else{
    echo "Did not work";
}
    $results = getAllMyRecipesAsList_recipeTable2($email, $recipeId);
    $_SESSION['recipeResults'] = $results;
    header('location:web_selected_recipe.php');
    exit();
?>

第二个 PHP 文件

 function getAllMyRecipesAsList_recipeTable2(string $email, int $recipeId){
    include 'config.php';
    $sql = 'SELECT * FROM recipeTable WHERE email = :email AND recipeId = :recipeId';
    $stmt = $conn->prepare($sql);       
    $stmt->bindParam(':email', $email, PDO::PARAM_STR);
    $stmt->bindParam(':recipeId', $recipeId, PDO::PARAM_STR);
    $stmt->execute();
    $getResults = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $json = array();
    if(count($getResults) > 0){
        foreach($getResults as $row){
            $json[] = array('firstName' => $row['firstName'],
                           'lastName' => $row['lastName'],
                           'email' => $row['email'],
                           'recipeName' => $row['recipeName'],
                           'description' => $row['description'],
                           'ingredients' => $row['ingredients'],
                           'prepTime' => $row['prepTime'],
                           'steps' => $row['steps'],
                           'nutrition' => $row['nutrition'],
                           'servings' => $row['servings'],
                           'rating' => $row['rating'],
                           'tags' => $row['tags'],
                           'imagePath' => $row['imagePath'],
                           'imageName' => $row['imageName'],
                           'recipeId' => $row['recipeId']
                           );
         }
        $results = json_encode($json);
        return $results;
    }else{
        echo "no data found";
    }
    }

然后在我的 JS 文件中检索(这只是相关部分):

<script>
    <?php $results = $_SESSION['recipeResults'];
var results = <?php echo $results; ?>;
    var toString = JSON.stringify(results);
    console.log(toString);
    var parsed = JSON.parse(toString);
    console.log(parsed);
</script>

记录 resultAsString 会产生以下结果:

[{"firstName":"Marcus","lastName":"Holden","email":"marcus@gmail.com","recipeName":"Aloo Paratha","description":"","ingredients":"","prepTime":"25 Minutes","steps":"","nutrition":"","servings":"","rating":"","tags":"","imagePath":"../userRecipeImages","imageName":"9110164.jpg","recipeId":"1"}]

记录解析后的结果是:

[{…}]
0:description:
"No Description", email "marcus@gmail.com", firstName:"Marcus", imageName:"9110164.jpg", imagePath:"../userRecipeImages", ingredients:"Some Ingredients",lastName:"Holden", nutrition:"Not given", prepTime:"25 Minutes", rating:"5/10", recipeId:"1", recipeName:"Aloo Paratha", servings: "6", steps:"Your Steps Here", tags:"It's bread"

现在,我已经尝试了所有步骤来获取与键关联的值...例如,我的对象在这里被称为已解析...所以我尝试了 parsed.firstName.. 返回未定义...以及 Object .keys(已解析)。我似乎拿不到 key 。我想像数组一样使用它...设置内容如下:

element.innerHTML = 已解析[2]...等

我在这里缺少什么?

最佳答案

我认为你做得比你需要做的要多得多。数据将以 JSON 编码的对象形式发送给您。只需使用它即可。

<script>
var results = <?php echo $_SESSION['recipeResults']; ?>;

var first_results = results[0]; // Each array member is one object from your result set
console.log( first_results.firstName );

console.log( results[0].firstName ); // OR specify which array index to interact directly
</script>

关于javascript - 无法从 Key JSON MySQL PHP 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48489429/

相关文章:

javascript - 在用户按顺序滚动时使用不透明度动画 SVG 路径

使用带有量词的字符类的 JavaScript 正则表达式

php - 如何在仅打印出有错误的文件时递归地检查所有文件?

php - PDO SQLITE转义单引号反斜杠

c++ - 将 reinterpret_cast 转换为 C 样式数组是否非法 C++11?

java - 迭代排序数组以删除重复项

javascript - javascript/node.js 中是否有与 python 的 inspect.getargspec 等效的东西?

javascript - 无法将坐标解析/投影到 JSON 上

Javascript 数据和 html 传输

javascript - 如果关联数组从正则表达式返回,则它是排序索引