Passing variable from ejs to js script

故事扮演 提交于 2019-12-25 02:44:29

问题


I am trying to pass a variable from ejs to JavaScript function but keep getting undefined in output. Here is the code. It is supposed to render a table with file names and clicking on each file name should later redirect to a page which would render the file in the browser but I can't proceed without passing the parameter to URL.

        <% if (files.length > 0) {%>
        <table class="table table-hovered">
            <thead class="thead-light">
                <tr>
                    <th scope="col">No</th>
                    <th scope="col">File</th>
                    <% files.forEach((file, index) => { %>
                <tr>
                    <th scope="row">
                        <%= index + 1 %>
                    </th>
                    <td>
                        <a onclick="func(file.fileName);">
                            <%= file.fileName %>
                        </a>
                    </td>
                </tr>
                <% }) %>
                </tbody>
        </table>
        <% } %>
    </div>
</div>
<script>
    function func(fileName) {
        window.location.href = "/thesis_view/" + fileName;
    }
</script>




getStudentUploadThesisPage: (req, res) => {
        const getFilesQuery = "SELECT fileName FROM supervision INNER JOIN thesis ON supervision.thesisId = thesis.id INNER JOIN thesis_details ON thesis_details.thesisId = thesis.Id INNER JOIN people ON supervision.teacherId = people.id INNER JOIN thesis_file ON thesis_details.id = thesis_file.thesis_detail_id WHERE supervision.studId = " + req.session.userId;
        db.query(getFilesQuery, (err, result) => {
            if (err) {
                return res.status(500).send(err);
            } else if (result.length >= 0) {
                res.render('student_upload_thesis', {
                    files: result
                });
            }
        });
    }

回答1:


I have come up with something like this. It does it job

<script>
    var table = document.getElementById('table'),
        rIndex;
    for (var i = 0; i < table.rows.length; i++) {
        table.rows[i].onclick = function () {
            rIndex = this.rowIndex;
            window.location.href = "/thesis_view/" + this.cells[1].innerHTML;
        }
    }
</script>


来源:https://stackoverflow.com/questions/54276174/passing-variable-from-ejs-to-js-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!