首页 > 解决方案 > 将 Python 输出打印到 HTML 中的特定 div

问题描述

我已经搜索了至少一个星期,但没有取得丰硕的成果。特别是,出现的主要方法是创建一个具有复杂文件结构的django项目,但我只是想用我现有的文件结构将一些Python字符串输出到特定的div(一个简单的由PHP组成的/HTML 文件、我的 Python 文件和我的 CSS/JS 文件夹)。然后我找到了这个结果,幸运的是,主要答案(向下滚动一点,它是@miniscruff)除了添加一些代码之外不需要任何复杂的东西。但是,它似乎不起作用。这是 PHP 的问题吗(因为@vickilanger 的文件是 HTML 文件而不是 PHP,并且她声称代码有效)?

我的index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie-edge">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css">
    <link rel="stylesheet" href="css/style.css?v=<?php echo time(); ?>">

    <!-- Font Awesome -->
    <link rel="stylesheet" href="//use.fontawesome.com/releases/v5.0.7/css/all.css">

    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Kalam&family=Pangolin&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">

    <!-- JQuery -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
    
    <title>Home</title>
</head>
<body>
    <div class="placeholder"></div>
    <script>
        $(function(){
            $('.placeholder').load("nav.html?v=<?php echo time(); ?>");
        });
    </script>    

    <code class="language-python match-braces" id="main-num">
        Fetching portfolio...
    </code>
    

    <script src="js/main.js"></script>


    <script>
        fetch("test.py")
            .then(response => {
                if(!response.ok) {
                    throw new Error("Bad Response")
                }
                return response.text()
            })
            .then(text => document.getElementById("main-num").innerText = text)
            .catch(error => document.getElementById("main-num").innerText = error)

    </script>
</body>
</html>

我的test.py

satisfy = [3, 6, 12, 53, 78, 586]
for num in satisfy:
 if num > 15:
  print(num)

此外,如果 dev.to 方法不起作用,还有其他简单的方法可以将 Python 打印到 HTML 吗?

标签: pythonphphtml

解决方案


推荐阅读