dongrang2140 2017-08-03 04:22
浏览 64
已采纳

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

Hi so currently I have a set of codes which dynamically creates HTML elements through AJAX using an external JSON data. When I created this, I wanted to store my data in an external file rather than in a database.

However, I now need to store them in mySQL so I was wondering how I can still dynamically create the HTML elements like this but now the data will be from mySQL instead of retrieving it from an external JSON file. I'm still quite new to this so I am really confused as to how to tackle this situation.

This is what my current code looks like:

 <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 Data:

 [  
        {  
          "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"
        }
]

When I tried pulling my data using PHP and encoding it to JSON, it gave me this result and it did not create any of the HTML elements needed.

enter image description here

  • 写回答

1条回答 默认 最新

  • douchixu3686 2017-08-03 05:11
    关注

    You can create a MySQL table like this,

    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`));
    

    Then you can use this query to insert your data,

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

    After that, you can create a PHP file to pull your data and print it in JSON format,

    You can give the PHP file a filename like,

    CR_QuickLookData.php
    

    With PHP code,

    <?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);
    

    Then in 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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 springboot+vue 集成keycloak sso到阿里云
  • ¥15 win7系统进入桌面过一秒后突然黑屏
  • ¥30 backtrader对于期货交易的现金和资产计算的问题
  • ¥15 求C# .net4.8小报表工具
  • ¥15 安装虚拟机时出现问题
  • ¥15 Selenium+docker Chrome不能运行
  • ¥15 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到
  • ¥15 请教一下,openwrt如何让同一usb储存设备拔插后设备符号不变?
  • ¥50 使用quartz框架进行分布式任务定时调度,启动了两个实例,但是只有一个实例参与调度,另外一个实例没有参与调度,不知道是为什么?请各位帮助看一下原因!!