javascript - Ajax 请求 : get text from database and display in div

标签 javascript php jquery html phpmyadmin

我的目标是在单击按钮时执行 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/

相关文章:

javascript - 如何获取html文本框的高亮颜色

javascript - 将平面 JSON 文件转换为分层 json 数据,如flare.json [d3 示例文件]

javascript - 如何测试返回函数值

php - 如何正确地将 mySQL 查询转换为 PDO

php - 将 sql 表内容从一个表复制到另一个表 - 有条件

php - 如何将变量存储在数据库中,然后在检索时插入它们

javascript - 样式在 javascript 中的变量中不起作用

javascript - HTML 表 : border-collapse and visibility collapse of tr

javascript - js退格并计算多少位数

asp.net-mvc-2 - 使用 jQuery 和 AJAX 将项目添加到 ASP.NET MVC 站点上的集合