我的目标是在单击按钮时执行 AJAX 请求以检索存储在我的数据库中的“名称”和“故事”。每个按钮都会获取另一个英雄的信息。 我正在处理多个文件。
使用我当前的代码(这更接近于我认为正确的代码)switchHeroInfo 将始终将文本更改为“TestName”和“< em>StoryName”而不是“Gertrude”“一位老太太”(存储在数据库中)。
您能告诉我我挣扎的原因是什么吗?
连接数据库的php文件:connect_database.php
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=biomass;charset=utf8', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch(Exception $e)
{
die('Error : '.$e->getMessage());
}
?>
Javascript 部分:
$(document).ready(function()
{
$(".hero_portrait").click(function()
{
var index = $(this).data("id");
$.ajax(
{
type: "POST",
url: "../php/get_data.php",
data: {newIndex:index},
success: function(data)
{
// Display {"nick":"Gertrude","0":"Gertrude","story":"Vieille folle senile","1":"Vieille folle senile"}
alert(data);
//Display : undefined
alert(data.story);
$("#hero_name").html(data.nick);
$("#hero_story").html(data.story);
},
error: function()
{
alert("Request failure");
}
});
});
});
php 文件:get_data.php
<?php
$tempValue = $_POST['newIndex'];
$sql = $bdd->prepare('SELECT * FROM heroes WHERE ID = :indexValue');
$sql->bindParam(":indexValue", $tempValue, PDO::PARAM_STR);
$sql->execute();
while($data = $sql->fetch())
{
?>
<script>
$heroNameTemp = <?php echo json_encode($data["name"]); ?>;
$heroStoryTemp = <?php echo json_encode($data["story"]); ?>;
</script>
<?php
}
$sql->closeCursor();
?>
最后是与当前问题相关的 HTML:
<div id="squad_portraits">
<div class="hero_portrait" id="1"></div>
<div class="hero_portrait" id="2"></div>
<div class="hero_portrait" id="3"></div>
<div class="hero_portrait" id="4"></div>
</div>
<div id="hero_info">
<h2 id="hero_name">Hero_Name</h2>
<p id="hero_story"> Hero_Description</p>
</div>
如果我切换我的 sql 请求:
$tempValue = $_POST['newIndex'];
$sql = $bdd->prepare('SELECT * FROM heroes WHERE ID = :indexValue');
对此
$tempValue = 4;
$sql = $bdd->prepare('SELECT * FROM heroes WHERE ID = 4');
并将以下内容添加到我的 HTML 文件中
<?php include("../php/get_data.php"); ?>
一切正常,但我的索引将始终为“4”。
最佳答案
您的代码中存在一些问题和误解。
首先,在 ajax 中将数据更改为:
data: {newIndex:index}, // remove the (), simple syntax misstake
这应该可以解决sql问题。
现在是 get_data.php:
<?php
// including db connection is missing here for $bdd
// You should add a test here, wether you've received any and correct data in 'newIndex'
if(empty($_POST['newIndex']) {
// throw an error, send that back to ajax (with a fitting http response code) and exit script
http_response_code(400);
$error = new stdClass();
$error->msg = "Parameter newIndex was missing";
header('Content-Type: application/json'); // tell the browser that there is some json coming!
echo json_encode($error);
exit;
}
$tempValue = $_POST['newIndex'];
// only select the values you need (name, story)
$sql = $bdd->prepare('SELECT name, story FROM heroes WHERE ID = :indexValue');
$sql->bindParam(":indexValue", $tempValue, PDO::PARAM_STR);
$sql->execute();
$data = $sql->fetch(); // if you only expect/need one row, no while is needed
// echo ONE json string as plain string:
header('Content-Type: application/json'); // tell the browser that there is some json coming!
echo json_encode($data);
现在您在 ajax 的成功回调中接收到 $data
的内容作为 json 作为参数 (data
),您可以像这样使用它:
success: function(data){
$("#hero_name").html(data.name);
$("#hero_story").html(data.story);
}
最后让我们将存储项目的 id 从 id 属性更改为 data-attribute:
在 html 中:
<div class="hero_portrait" data-id="1"></div>
<div class="hero_portrait" data-id="2"></div>
并在 javascript 中更改
var index = $(this).attr("id");
到
var index = $(this).data("id"); // $(this).attr("data-id"); will also work
关于javascript - Ajax 请求 : get text from database and display in div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53502438/