简体   繁体   English

使用 nodeJS 单击获取数组索引/如何删除 nodeJS 服务器上的留言簿条目

[英]Get array index on click with nodeJS / How do I delete a guestbook entry on my nodeJS server

I followed a tutorial to build a small guestbook with nodeJS and ajax, now I am trying to extend it a little with adding features such as deleting a particular entry on click of a button, but my problem is how do I get the array index of the entry I clicked on??我按照教程使用 nodeJS 和 ajax 构建了一个小型留言簿,现在我试图通过添加一些功能来扩展它,例如在单击按钮时删除特定条目,但我的问题是如何获取数组索引我点击的条目?? I know I can get it in my JS file with我知道我可以在我的 JS 文件中使用它

$('.entrygrid .entry .del').click(function() {
    console.log($(this).parent().parent().index());
});

but how would I then get this value in my server file?但是我如何在我的服务器文件中获得这个值? so that I can delete the [array index i clicked] item in my JSON file?以便我可以删除 JSON 文件中的 [array index i clicked] 项目?

this is the code I got so far and it's all working but I want to delete entries.这是我到目前为止得到的代码,它都在工作,但我想删除条目。 ( i know my code looks terrible it's my first time doing anything with node.js ) (我知道我的代码看起来很糟糕,这是我第一次用 node.js 做任何事情)

app.js应用程序.js

'use strict';

let idk = require('./idk.js'); // lol
let express = require('express');
let bodyParser = require('body-parser');
let GuestbookEntry = require('./src/GuestbookEntry.js'); // guestbook requirement
let fs = require('fs');

fs.readFile('./data.json', 'utf-8', (err, data) => {
    if (err) throw err;
    let d = JSON.parse(data);

    let entries = [];
    for(let entry of d) {
        entries.push(new GuestbookEntry(entry.author, entry.title, entry.content, entry.date));
    }

    // Start Server

    let app = express();
    app.set('view engine', 'ejs');
    app.set('views', './views');

    app.use(bodyParser.urlencoded({extended: true}));
    app.use(express.static('./public'));


    let text;

    if (entries.length < 2) {
        text = 'entry';
    } else {
        text = 'entries';
    }

    app.get('/index', (req, res) => {
        res.render('index', {
            entries: entries,
            text: text
        });
    });

    app.post('/guestbook/new', (req, res) => {
        let tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
        let localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -1);

        let currentDate = localISOTime.slice(0, 10).replace(/-/g, "/");
        let currentTime = localISOTime.slice(11, 19);

        let date = currentDate + ", " + currentTime;
        let content = req.body.content;
        let title = req.body.title;
        let author = req.body.author;

        let newEntry = new GuestbookEntry(author, title, content, date);
        entries.push(newEntry);

        // write data into the file data json
        fs.writeFileSync('./data.json', JSON.stringify(entries));

        res.redirect('/index');
        if (entries.length < 2) {
            text = 'entry';
        } else {
            text = 'entries';
        }

    });

    app.post('/guestbook/del', (req, res) => {
        //delete the entry please
    });

    app.listen(1337, () => {
        console.log('oof');
    });

});

data.json数据.json

[{
    "author": "a",
    "title": "a",
    "content": "a",
    "date": "2020/01/30, 08:40:07"
}, {
    "author": "test",
    "title": "test",
    "content": "test",
    "date": "2020/01/30, 08:41:24"
}, {
    "author": "test",
    "title": "test",
    "content": "test",
    "date": "2020/01/30, 08:42:23"
}]

GuestbookEntry.js留言簿Entry.js

"use strict";

class GuestbookEntry {
    constructor(author, title, content, date) {
        this.author = author;
        this.title = title; 
        this.content = content;
        this.date = date;
    }
}

module.exports = GuestbookEntry;

index.ejs索引.ejs

<html>
    <head>
        <title>index</title>
        <link rel="stylesheet" href="/css/app.css">
    </head>
    <body>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
        <script src="/js/index.js"></script>
        <div class="all">
            <div class="main">
                <h1>node.js ,,,</h1>
                <a href="http://localhost:1337/gay">gay</a>

                <div class="entrycount"><span></span></div>
                <div class="entrygrid">
                <% for(let entry of entries) { %>
                    <div class="entry">
                        <strong><%= entry.author %></strong>
                        <h3><%= entry.title %></h3>
                        <p><%= entry.content %></p>
                        <p><%= entry.date %></p>
                        <form method="POST" action="/guestbook/del">
                        <button class="del" type="submit"></button>
                        </form>
                    </div>
                <% } %>
                </div>

                <form class="new-entry" method="POST" action="/guestbook/new">
                    <input type="text" name="author" placeholder="Author">
                    <input type="text" name="title" placeholder="Title">
                    <textarea name="content" placeholder="Your text here!" rows="5" cols="20" ></textarea>
                    <button type="submit">Send!</button>
                </form>
            </div>
        </div>
    </body>
</html>

index.js索引.js

$(document).ready(function(){

    let currentDate;
    let currentTime;
    let tzoffset;
    let localISOTime;
    let text;

    if ($('.entrygrid .entry').length < 2) {
        text = "entry";
    } else {
        text = "entries";
    }

    $('.entrycount span').text($('.entrygrid .entry').length + " " + text);

    /*$(".new-entry").submit(function(e) {
        e.preventDefault();

        tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
        localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -1);

        currentDate = localISOTime.slice(0, 10).replace(/-/g, "/");
        currentTime = localISOTime.slice(11, 19);

        let author = $('input[name="author"]').val();
        let title = $('input[name="title"]').val();
        let content = $('textarea[name="content"]').val();
        let date = currentDate + ", " + currentTime;

        $.ajax({
            url: '/guestbook/new',
            method: "POST",
            data: {
                "author": author,
                "title": title,
                "content": content,
                "date": date,
            },
            success: function(data) {
                let div = $.parseHTML("<div></div>");
                $(div).html(data);

                let newEntries = $(".entry", div);

                $(".entrygrid .entry").remove();

                newEntries.each(function(i, newEntry) {
                    $(".entrygrid").append(newEntry);
                });
                $('.entrycount span').text($('.entrygrid .entry').length);
                //console.log(data);
            }
        });
        //alert(author + " " + title + " " + content);
    });*/



});

You need to fetch the index when you are looping through the content of your JSON-file.当您循环浏览 JSON 文件的内容时,您需要获取索引。 Then you could use that to create a new key for index in your Guestbook object, name the elements or similar.然后,您可以使用它为留言簿对象中的索引创建新键,命名元素或类似内容。 I would do it like this:我会这样做:

d.forEach((element, index) => {
  //Do Something with the index
});

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

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