基于mySQL数据动态创建HTML元素

时间:2017-08-03 04:22:46

标签: php mysql json

您好,目前我有一组代码,可以使用外部JSON数据通过AJAX动态创建HTML元素。当我创建它时,我想将我的数据存储在外部文件而不是数据库中。

但是,我现在需要将它们存储在mySQL中,所以我想知道如何仍然可以像这样动态创建HTML元素,但现在数据将来自mySQL而不是从外部JSON文件中检索它。我对此仍然很陌生,所以我对如何处理这种情况感到很困惑。

这是我目前的代码:

 <script>
        $.ajax({
          url : "CR/CR_Data/CR_QuickLookData.json",
          type : "post", 
          contentType:"application/json", 
          success : function(list){           
              var divCol  = "<div class='col-sm-4 col-md-4'>";
              var divWell = "<div class='well' style='position:relative'>";
              var divClose = "</div>";

              console.log(list);

                list.forEach(function(obj, index) {

                //console.log(obj); 

                var title     = "<h5>"      + obj.title    + "</h5>";
                var linkStart = "<a href='" + obj.imagePath + "' rel='lightbox' title='" + obj.title + "'>"
                var image     = "<img data-toggle='tooltip' data-placement='left' class='wellImg' title='Click to enlarge image' src='" + obj.imagePath + "'/>"
                var desc      = "<p>"       + obj.desc + "</p>";
                var linkEnd   = "</a>";

                var div = divCol    +
                divWell     +
                title       +
                linkStart        +
                image       +
                desc +
                linkEnd     +
                divClose +
                divClose;

               $("#CR").append(div); // insert the div you've just created

               })
            }
        });
      </script>

JSON数据:

 [  
        {  
          "team":"Team Name",
          "title":"Title",
          "filePath":"#",
          "imagePath":"image path",
          "desc":"Data Description"
        },
        {  
          "team":"Team Name",
          "title":"Title",
          "filePath":"#",
          "imagePath":"image path",
          "desc":"Data Description"
        },
        {  
          "team":"Team Name",
          "title":"Title",
          "filePath":"#",
          "imagePath":"image path",
          "desc":"Data Description"
        }
]

当我尝试使用PHP提取数据并将其编码为JSON时,它给了我这个结果并且它没有创建任何所需的HTML元素。

enter image description here

1 个答案:

答案 0 :(得分:2)

你可以像这样创建一个MySQL表,

CREATE TABLE `record` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `team` TEXT NULL,
  `title` TEXT NULL,
  `filePath` TEXT NULL,
  `imagePath` TEXT NULL,
  `desc` TEXT NULL,
  PRIMARY KEY (`id`));

然后您可以使用此查询来插入数据

INSERT INTO `record` (`team`, `title`, `filePath`, `imagePath`, `desc`) VALUES ('Team Name', 'Title', '#', 'image path', 'Data Description');

之后,您可以创建一个PHP文件来提取数据并以JSON格式打印

您可以为PHP文件指定文件名,

CR_QuickLookData.php

使用PHP代码,

<?php

$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()){
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="SELECT team,title,filePath,imagePath,`desc`  FROM record";
$result=mysqli_query($con,$sql);

$list = array();
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
    $list[] = array (
        'team' => $row['team'],
        'title' => $row['title'],
        'filePath' => $row['filePath'],
        'imagePath' => $row['imagePath'],
        'desc' => $row['desc']
    );
}

mysqli_free_result($result);
mysqli_close($con);


echo json_encode($list);

然后在index.html中,

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
    <div id="CR"></div>
    <script>
        $(window).ready(function(e) {
            $.ajax({
                url : "CR_QuickLookData.php",
                type : "post", 
                dataType: "json",
                success : function(list){           
                    var divCol  = "<div class='col-sm-4 col-md-4'>";
                    var divWell = "<div class='well' style='position:relative'>";
                    var divClose = "</div>";

                    list.forEach(function(obj, index) {
                        var title     = "<h5>"      + obj.title    + "</h5>";
                        var linkStart = "<a href='" + obj.imagePath + "' rel='lightbox' title='" + obj.title + "'>"
                        var image     = "<img data-toggle='tooltip' data-placement='left' class='wellImg' title='Click to enlarge image' src='" + obj.imagePath + "'/>"
                        var desc      = "<p>"       + obj.desc + "</p>";
                        var linkEnd   = "</a>";

                        var div = divCol    +
                        divWell     +
                        title       +
                        linkStart        +
                        image       +
                        desc +
                        linkEnd     +
                        divClose +
                        divClose;

                        $("#CR").append(div); // insert the div you've just created
                    });
                }
            });
        });
    </script>
</body>
</html>