ejs 中的函数,变量传递给 HTML

function in ejs with variable passed trought to HTML

我是 node.js 的新手,我正在尝试让我的页面在单击按钮时播放歌曲。 问题是这首歌没有播放,我不确定是否一切都通过了正确的方式。

我在我的控制台中得到的是该页面正在尝试获取 xxx.mp3,但给出了 404。

    <!DOCTYPE html>
<html>
    <head>
        <title><%= title%></title>
        <link rel='stylesheet' href='/stylesheets/style.css' />
    </head>

    <script>
        function playIt(song)
        {
            document.getElementById("embed").innerHTML="<audio src=\""+song+".mp3\" autoplay> <embed src=\""+song+".mp3\" hidden=\"true\" /> </audio>";
            return true;
        }
    </script>

    <body>

<% include templates/header.ejs %>
<h1><%= title%></h1>

<h3><%= muziek.Artist%> - <%= muziek.Album %></h3>

<div class="CSS_Table_Example" style="width:600px;height:720px;">

    <table>
        <tr>
            <td width="20px"><h4>Nr</h4></td>
            <td width="110px"><h4>Title</h4></td>
            <td width="100px"><h4>Album</h4></td>
            <td width="100px"><h4>Artist</h4></td>
            <td width="100px"><h4>Length</h4></td>
            <td><h4>Play</h4></td>
        </tr>
        <tr>
            <% muziek.categories.forEach(function(item){ %>
            <td width="20px"><%= item.albumNumber %></td>
            <td width="150px"><%= item.title %></td>
            <td width="100px"><%= item.album %></td>
            <td width="100px"><%= item.artist %></td>
            <td width="100px"><%= item.length %></td>
            <td>
                <form action="" method="post">
                    <button type="button" class="myButton" style="width: 250px" onclick="playIt(<%= item.albumNumber%>)">play <%= item.title%></button>
                </form>
            </td>
        </tr>
        <% }); %>
    </table>
</div>

<div id="embed"></div>

    </body>
</html>

我不确定我是否可以在 ejs 中使用 <script> 标签? 歌曲在主文件夹中,名称为 1.mp3、2.mp3 等等。

提前致谢,

托马斯

您的服务器配置如下:

app.use(express.static(path.join(__dirname, 'public')));

您在问题中陈述:

the songs are in the main folder

如果"main folder"指的是app.js所在的文件夹,那么MP3文件是找不到的,因为你已经让静态中间件去查找了在一个名为 public/ 的目录中(相对于主文件夹)。

将 MP3 文件移动到 public/ 并重试。