我正在使用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 ..返回undefined ...以及Object .keys(解析)。我似乎无法获得钥匙。我想像数组一样使用它...设置这样的内容:
element.innerHTML =已解析[2] ......等等。
我在这里缺少什么?
答案 0 :(得分:1)
我认为你做的比你需要的要多得多。数据作为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>