繁体   English   中英

如何将我的 html 代码连接到 javascript 中的控制器和路由?

[英]How do I connect my html code to controllers and routes in javascript?

HTML 代码需要做前端。

它应该接受用户的输入和需要转换为 JSON 格式并发布在服务器上的文件上的信息。

我还需要能够通过我的 HTML 页面本身来编辑 json 文件。

    <!DOCTYPE html>
    <html>

    <head>
    <title>
        News
    </title>
    <link rel="stylesheet" href="style.css">
    </head>

    <body>

    <h1><center>News Form</center></h1>
    <hr>
            <div class="news-form">
                <form onsubmit="event.preventDefault();onFormSubmit();" autocomplete="off">
                    <div>
                        <label for="trending">Trending?</label><br>

                        <select name="trending" id="trending">
                        <option value="yes">yes</option>
                        <option value="no">no</option>
                        
                        </select> <br>  
                       
                    </div>
                    <div><br>
                        <label>Image Link</label><label class="validation-error hide"   id="ValidationError">This field is required!</label>
                        <input type="text" name="image" id="image">
                    </div>
                    <div>
                        <label>Heading</label>
                        <input type="text" name="heading" id="heading">
                    </div>
                    <div>
                        <label>Content</label>
                        <input type="text" name="content" id="content">
                    </div> <br>
                    <div>
                        <label for="genres">Choose a category:</label>
                         <br>   
                        <select name="genres" id="genres">
                        <option value="finance">finance</option>
                        <option value="politics">politics</option>
                        <option value="sports">sports</option>
                        <option value="business">business</option>
                        </select>
                        
                    </div>
                    <div  class="form-action-buttons">
                        <input type="submit" value="Submit">
                    </div>
                </form>
        </div>
        <br/>
        <div class = "news-table">
                <table class="list" id="newsList">
                    <thead>
                        <tr>
                            <th>Trending</th>
                            <th>Image Link</th>
                            <th>Heading</th>
                            <th>Content</th>
                            <th>Genres</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>

                    </tbody>
                </table>
        </div>
       <script src="script.js"></script>
       </body>
       </html>

Controller 应该从 HTML 页面获取数据并发送到服务器:


    import { v4 as uuidv4 } from 'uuid';
    let users =[]

    export const createNews =(req,res) =>{
                                        const newuser= req.content;
                                                                                   
                                        users.push({...newuser, id: uuidv4()});
                                        console.log('post route reached');
                                                                                   
                                        res.send(`User with the heading ${newuser.heading} added to  the database!`);}


    export const getNewsonid =(req,res)=>{
                                        const {id} = req.params;
                                        const founduser= users.find((newuser) => newuser.id = id );
                                        console.log(req.params);
                                          
                                        res.send(founduser);
                                        res.send('THE GET ID ROUTE');                     
    }

    export const deleteNews =(req,res)=>{
                                        const {id} = req.params ;
                                        users = users.filter((newuser)=>newuser.id != id);
                                        res.send(`User with id ${id} deleted from the database`);
        
    }

    export const updateNews =(req,res)=>{
                                        const {id} = req.params ;
                                        const newuser= users.find((newuser)=>newuser.id = id);
                                        const {heading,trending,category,content} = req.body;
                                        if (heading) newuser.heading =heading;
                                        if (trending) newuser.trending =trending;
                                        if (category) newuser.category=category;
                                        if (content) newuser.content=content;
                                        res.send(`User with ${id}, has been updated!`)     
     }

     export const getAllNews =(req,res)=>{
                                        res.send(users);
                                        console.log('printed');                                 
     }

路线 javascript 文件:

    import express from 'express';
    import {createNews} from "../controllers/users.js";
    import {getNewsonid} from "../controllers/users.js";
    import {deleteNews} from "../controllers/users.js";
    import {updateNews,getAllNews} from "../controllers/users.js";

     const router = express.Router();

    router.get('/',getAllNews);                                  
    router.post('/',createNews);
    router.get('/:id',getNewsonid);
    router.delete('/:id',deleteNews)
    router.patch('/:id',updateNews)

    export default router;

服务器代码:

     import express from 'express';
     import bodyParser from 'body-Parser';
     import usersRoutes from './routes/users.js';
     const app = express();
     const port = 5000;
     import http from 'http';

     import path from 'path';
     import { fileURLToPath } from 'url';
     const __filename = fileURLToPath(import.meta.url);
     const __dirname = path.dirname(__filename);

    app.use(bodyParser.json());// we will be using json to convey and accept our requests

     app.get('/',function(req,res) {
      res.sendFile('/index.html', { root: __dirname });
     });

    app.use('/users',usersRoutes);

    app.listen(port, () =>{
                        console.log(`Server Running on port : http://localhost:${port}`)                  
    })

    app.get('/',(req,res)=>{
             console.log('Print on terminal');
             res.send(`Server Running on port : http://localhost:${port}`)                             
    });

我还需要连接此脚本文件,以便可以从 HTML 文件本身查看和编辑 JSON 上发送的信息。

    var selectedRow = null

    function onFormSubmit() {
    if (validate()) {
        var formData = readFormData();
        if (selectedRow == null)
            insertNewRecord(formData);
        else
            updateRecord(formData);
        resetForm();
    }
    }

    function readFormData() {
    var formData = {};
    formData["trending"] = document.getElementById("trending").value;
    formData["image"] = document.getElementById("image").value;
    formData["heading"] = document.getElementById("heading").value;
    formData["content"] = document.getElementById("content").value;
    formData["genres"] = document.getElementById("genres").value;
    return formData;
    }

    function insertNewRecord(data) {
    var table = document.getElementById("newsList").getElementsByTagName('tbody')[0];
    var newRow = table.insertRow(table.length);
    cell0 = newRow.insertCell(0);
    cell0.innerHTML = data.trending;
    cell1 = newRow.insertCell(1);
    cell1.innerHTML = data.image;
    cell2 = newRow.insertCell(2);
    cell2.innerHTML = data.heading;
    cell3 = newRow.insertCell(3);
    cell3.innerHTML = data.content;
    cell4 = newRow.insertCell(4);
    cell4.innerHTML = data.genres;
    cell4 = newRow.insertCell(5);
    cell4.innerHTML = `<a onClick="onEdit(this)">Edit</a>
                       <a onClick="onDelete(this)">Delete</a>`;
    }

    function resetForm() {
    document.getElementById("trending").value = "";
    document.getElementById("image").value = "";
    document.getElementById("heading").value = "";
    document.getElementById("content").value = "";
    document.getElementById("genres").value = "";
    selectedRow = null;
    }

    function onEdit(td) {
    selectedRow = td.parentElement.parentElement;
    document.getElementById("trending").value = selectedRow.cells[0].innerHTML;
    document.getElementById("image").value = selectedRow.cells[1].innerHTML;
    document.getElementById("heading").value = selectedRow.cells[2].innerHTML;
    document.getElementById("content").value = selectedRow.cells[3].innerHTML;
    document.getElementById("genres").value = selectedRow.cells[4].innerHTML; 
    }
     function updateRecord(formData) {
    selectedRow.cells[0].innerHTML = formData.trending;
    selectedRow.cells[1].innerHTML = formData.image;
    selectedRow.cells[2].innerHTML = formData.heading;
    selectedRow.cells[3].innerHTML = formData.content;
    selectedRow.cells[4].innerHTML = formData.genres;
    }

    function onDelete(td) {
    if (confirm('Are you sure to delete this record ?')) {
        row = td.parentElement.parentElement;
        document.getElementById("newsList").deleteRow(row.rowIndex);
        resetForm();
    }
    }
    function validate() {
    isValid = true;
    if (document.getElementById("image").value == "") {
        isValid = false;
        document.getElementById("ValidationError").classList.remove("hide");
    } else {
        isValid = true;
        if (!document.getElementById("ValidationError").classList.contains("hide"))
            document.getElementById("ValidationError").classList.add("hide");
    }
    return isValid;
    }

我一直在尝试过去 5 天,但无济于事。 请提供有关如何建立连接并使其工作的任何反馈。

我也不断收到 MIME 错误。 然后我将 javascript 文件直接添加到 HTML 页面,但随后显示 UnCaught Reference: onFormSubmit not defined。

我也收到错误消息:来自 onMessage 侦听器的承诺响应超出 scope

AFAIN,连接是 html 文件,在 head 或 body 中作为最后一个条目。

像这个不完整的示例index.html和脚本:

<!DOCTYPE html>
<html>

<!-- START. Your html code -->

<head>
    <!-- Favicon-->
    <link rel="icon" type="image/x-icon" href="/static/assets/favicon.ico" />
    <!-- Font Awesome icons (free version)-->
    <script src="https://use.fontawesome.com/releases/v5.15.3/js/all.js" crossorigin="anonymous"></script>

</head>
<body>

<!-- END. Your html code -->

    <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="/static/js/scripts.js"></script>
    <script src="/static/js/jqBootstrapValidation.js"></script>
    <script src="/static/js/contact_me.js" type="text/javascript"></script>
<!--  -->

</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM