将表单提交推送到数组

时间:2018-05-15 18:03:55

标签: javascript

我有一个包含2个部分的博客:帖子和要发布的表单。存在一系列对象,其中存储了后期数据(作者,日期,内容,标题)。我希望能够使用表单将新条目推送到posts数组,并在刷新页面时显示新数组。我能这样做吗?如果没有,这个问题应该如何解决?我无法使用服务器,所有文件都必须是本地的。

var posts = [{
        author: "Gabriel Alexandrescu",
        title: "Prajiturile cu ciocolata",
        content: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi felis magna, sodales commodo varius a, \
        pulvinar ac enim. Etiam vitae tortor eleifend, mollis magna id, venenatis purus. Nam vestibulum feugiat \
        condimentum. Nulla volutpat lacus et urna vehicula, eu accumsan nibh iaculis. Sed quis efficitur leo, in \
        malesuada sem. Etiam interdum velit justo, eget congue eros molestie sit amet. Nulla et tincidunt nibh.",
        date: "04/02/2018"
    },
    {
        author: "Laura Oprisan",
        title: "Masinile hybrid",
        date: "12/03/2018",
        content: "Nulla facilisi. Morbi urna mi, commodo a lacus at, rhoncus malesuada mi. Vivamus accumsan tempus \
        magna vitae pellentesque. Morbi rutrum risus ligula, ac posuere est finibus eu. Duis semper porta magna, \
        eget pulvinar neque lacinia vitae. Vestibulum luctus sollicitudin nisl, in hendrerit lacus vehicula eu. \
        Curabitur venenatis ipsum ut dignissim consectetur. Ut pellentesque vitae nulla eu finibus. Nulla facilisi. \
        Suspendisse sem nibh, tristique nec venenatis sed, fringilla at libero. Nullam et nisl eget urna sodales \
        semper sit amet eu ex. Quisque ut risus eget metus porta euismod. Nam imperdiet ipsum non tortor maximus, \
        non varius lacus commodo. Nam rutrum tellus metus, et luctus ex facilisis efficitur. Suspendisse ut augue \
        porta ex suscipit varius sed et metus."
    },
    {
        author: "Alin Popescu",
        title: "Cafeaua in ziua de azi",
        date: "10/05/2018",
        content: "Integer mi ante, luctus quis sagittis nec, rhoncus elementum magna. Morbi ultricies consequat urna. \
        Pellentesque at lorem sed neque sodales vehicula. Nam massa lectus, pharetra et feugiat non, pellentesque in \
        elit. Donec consectetur iaculis neque, ac pharetra turpis. Sed molestie mauris et arcu ultrices, vitae vehicula \
        erat rutrum. Quisque justo massa, rhoncus rhoncus imperdiet vitae, blandit vitae magna."
    }
]

function renderPosts() {
    let postsList = document.getElementById("postsList");
    posts.forEach((element, index) => {
        postsList.innerHTML += `<li>
        <div class="card">
            <h3 class="noMargin">
                ${element.title}
            </h3>
            <h5 class="noMargin">By
                ${element.author} |
                    ${element.date}
            </h5>
            <p>
                ${element.content}
            </p>
        </div>
    </li>`;
    });
}

function start() {
    renderPosts();
}

function submit() {
    var nowDate = new Date();
    var formattedDate = nowDate.getDate() + '/' + (nowDate.getMonth() + 1) + '/' + nowDate.getFullYear();

    var newAuthor = document.getElementById("form").elements[0].value;
    var newtitle = document.getElementById("form").elements[1].value;
    var newContent = document.getElementById("form").elements[2].value;

    var newPost = {
        author: newAuthor,
        title: newTitle,
        content: newContent,
        date: formattedDate
    }
    posts.push(newPost);
    location.reload();
}

window.addEventListener("load", start);
<h1>Add post</h1>
            <form class="form" id="form">
                <label>Author</label>
                <br>
                <input type="text" name="author" id="author" class="otherFields">
                <br>
                <label>Title</label>
                <br>
                <input type="text" name="title" class="otherFields">
                <br>
                <label>Content</label>
                <br>
                <input type="text" name="content" class="contentField">
                <br>
                <input type="submit" value="submit" class="submit" onClick="submit()">
            </form>

2 个答案:

答案 0 :(得分:1)

我会考虑使用local storage。除非您要将值附加到get请求中,否则您将需要在页面重新加载时使用某种类型的存储(由于示例数据中的描述有多长,这可能无法实现)。

本地存储将在浏览器存储中设置值,可以在重新加载时获取它们。

posts = {};
if(localStorage.getItem('posts')) {
    posts = json.parse(localStorage.getItem('posts'));
    renderPosts();
}
这样的事情会让你开始从本地存储中取出。

答案 1 :(得分:0)

您的方法仅限于客户方。 这里有一个简单但功能性的例子https://jsfiddle.net/jeu0kbbq/,而不需要先设置帖子:

 if(localStorage.getItem("posts")){
            posts = JSON.parse(localStorage.getItem("posts")); 
        }else{
            posts = [];
            localStorage.setItem("posts", JSON.stringify(posts));
        }

当然使用localStorage并且没有服务器端代码和/或数据库客户端根本无法共享信息。信息存储在客户端浏览器中,每个浏览器都有自己的信息。

我认为这只是为客户提供安全管理信息的好方法,因为根本没有网络活动。