Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 在使用Ajax的Nodejs Express项目中提交失败后保存表单输入时遇到问题_Html_Jquery_Node.js_Ajax_Forms - Fatal编程技术网

Html 在使用Ajax的Nodejs Express项目中提交失败后保存表单输入时遇到问题

Html 在使用Ajax的Nodejs Express项目中提交失败后保存表单输入时遇到问题,html,jquery,node.js,ajax,forms,Html,Jquery,Node.js,Ajax,Forms,我目前正在从事一个Nodejs项目,我正在尝试获取表单中输入的信息,以便在提交失败后在表单中重新显示。然而,我对如何准确执行这一点感到困惑。通过研究,我了解到通过Ajax请求来实现这一点是我最好的选择。我看过其他的帖子,也在谷歌上搜索过,但都没有运气。有人能帮我吗?这是指向项目回购的链接:。我还发布了本回购协议中可能更新或不更新的任何相关代码 $(document).ready(function(){ $("#createRecipeForm").submit(fun

我目前正在从事一个Nodejs项目,我正在尝试获取表单中输入的信息,以便在提交失败后在表单中重新显示。然而,我对如何准确执行这一点感到困惑。通过研究,我了解到通过Ajax请求来实现这一点是我最好的选择。我看过其他的帖子,也在谷歌上搜索过,但都没有运气。有人能帮我吗?这是指向项目回购的链接:。我还发布了本回购协议中可能更新或不更新的任何相关代码

$(document).ready(function(){
    $("#createRecipeForm").submit(function(e) {

        $.ajax({
             type: "POST",
             url: "/recipes/createRecipe",
             data: $(this).serialize(), // serializes form input
             success: function(data){
                console.log(data);
             },
             error: function(data){
                console.log(data);
             }
        });

        console.log(data);
    });

});
编辑3:


您可以在发出请求之前使用localStorage设置表单详细信息,然后在请求成功时清除请求,或者在请求失败时获取数据

试试这个

$(文档).ready(函数(){
//您有标题、图像、描述、成分、说明等表单输入
//从表单中获取输入是这样的
常数数据={
标题:$('#recipeNameInput').val(),//此语法用于从jquery获取输入数据
image:$('#recipeNameInput').val(),//其中#符号表示正在使用id获取值
说明:$(“#RecipedDescriptionInput”).val(),
成分:$('#IngreditInput').val()),
方向:$('#directionInput').val(),//在配料和方向的情况下,您使用的是Vue的'v-model',但我假设您的文本id分别为'IngreditInput'和'directionInput'
}
localStorage.setItem('data',JSON.stringify(data))//假定数据是数组或对象
$(“#createRecipeForm”).submit(函数(e){
$.ajax({
类型:“POST”,
url:“/recipes/createRecipe”,
数据:$(this).serialize(),//序列化表单输入
成功:功能(数据){
localStorage.removeItem('data')//清除localStorage中的数据,因为不再需要这些数据
//做另一件事
},
错误:函数(数据){
//抛出或返回错误消息
}
});
});

});我知道你的逻辑来自哪里,它向我澄清了一些事情。但是,当我尝试使用上面的第一段jquery代码时,我的控制台显示了一个错误,我在上面文章的底部链接了这个错误。很抱歉,我没有说清楚<代码>数据
是保存表单数据的变量。你可以给它取任何你喜欢的名字。我只是为了这个例子而使用“数据”。你现在明白了吗?这同样适用于我使用的localStorage密钥。您不必将其命名为“数据”。你可以用任何你喜欢的名字。很抱歉给你添麻烦,我对这个不熟悉。我有几个问题。如何准确保存表单数据?并且,在将其保存到变量中之后,我现在是否能够访问作为数组存储在其中的信息?谢谢你,我明白了,哈尔谢赫。我已经更新了我的答案。我注意到您正在同时使用Vue和jQuery。这不是一个很好的实践,因为Vue和jQuery可以用来实现几乎相同的目标。我将建议您暂时停止使用React.js、Vue.js等js框架,因为您是新手。在使用像Vue这样的框架之前,尝试使用香草javascript并理解引擎盖下发生的事情。感谢您的输入。我现在在稍后的代码编写中意识到,使用Due和jQuery都是不好的做法,我已经计划取消对Vue的使用。我正在尽我最大的努力使用香草,然而,仅仅使用香草是无法完成一些事情的。我非常感谢你的帮助。现在,我已经能够使用您与我共享的代码来检索表单信息,但是,我将数据变量和该变量的存储移动到表单提交调用中,因为除非我这样做,否则它不会接收变量。我现在的问题是我无法重新发现。。。
<!DOCTYPE html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Homemade</title>

        <!-- Required program scripts -->
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
        
        <!-- Style Sheets-->
        <link rel="stylesheet" href="/styles/navBarStyle.css">
        <link rel="stylesheet" href="/styles/myRecipesStyle.css">
        <link rel="stylesheet" href="/styles/createRecipeStyle.css">
    </head>
    <body>
        <!-- Background image -->
        <img id="background" src="/images/foodBackground.jpg" alt="">

        <div id="newRecipeContainer">
            <div id="closeButtonContainer">
                <div id="backButton"><a id="back" href="/recipes/myRecipes">&larr; My Recipes</a></div>
            </div>
            
            <form id="createRecipeForm" action="/recipes/createRecipe" method="POST" enctype="multipart/form-data">
                <label id="formSubHeading">Create Your Homemade Recipe</label>

                <div id="recipeNameContainer">
                    <label id="recipeNameLabel">Title</label>
                    <input id="recipeNameInput" type="text" name="recipeName">
                </div>

                <div id="recipeImage">
                    <label id="recipeImageLabel">Add An Image of Your Meal</label>
                    <input id="recipeImageInput" type="file" accept="image/*" name="recipeImage"/> 
                    <label id="recipeImageInputLabel" for="recipeImageInput" name="recipeImage">Choose A File</label>
                </div>

                <div id="recipeDescription">
                    <label id="recipeDescriptionLabel">Description</label>
                    <textarea id="recipeDescriptionInput" name="recipeDescription" cols="30" rows="10" maxlength="2000"></textarea>
                </div>

                <div class="ingredientsContainer">
                    <label id="ingredientsLabel">Ingredients</label>
                    <button id="addIngredientButton" type="button" @click="addIngredientForm">Add Another Ingredient</button>
            
                    <div class="allIngredients" v-for="(ingredient, ingredientIndex) in ingredients">
                        <label class="ingredientLabel">{{ ingredientIndex + 1 }}.)</label>
                        <input class="ingredientInput" type="text" name="ingredients" v-model="ingredient.ingredient">
                        
                        <button class="deleteIngredientButton" type="button" v-if="ingredientIndex > 0" @click="deleteIngredientForm(ingredientIndex)">X</button>
                    </div>
                </div>

                <div class="directionsContainer">
                    <label id="directionsLabel">Directions</label>
                    <button id="addDirectionButton" type="button" @click="addDirectionForm">Add Another Direction</button>
            
                    <div class="allDirections" v-for="(direction, directionIndex) in directions">
                        <label class="directionLabel">{{ directionIndex + 1 }}.)</label>
                        <input class="directionInput"type="text" name="directions" v-model="direction.direction">
                        
                        <button class="deleteDirectionButton" type="button" v-if="directionIndex > 0" @click="deleteDirectionForm(directionIndex)">X</button>
                    </div>
                </div>
                
                <div id="createRecipeButtonContainer">
                    <button id="createRecipeButton" type="submit">Create Recipe</button>
                </div>
                
            </form>
        </div>
    </body>
    
    <script src="/controls/newRecipeControl.js"></script>
</html>
$(document).ready(function(){
    $("#createRecipeForm").submit(function(e) {
        const data = {
            title: $('#recipeNameInput').val(), // this syntax is for grabbing input data from jquery
            image: $('imageNameInput').val(), // where the # sign indicates an id is being used to grab the value
            description: $('#recipeDescriptionInput').val(),
            ingredients: $('#ingredientInput').val(),
            directions: $('#directionInput').val(), // in the cases of ingredients and directions, you are using Vue's `v-model` but I am going to assume you have text id's of `ingredientInput` and `directionInput` for them respectively
        };
    
        console.log(data);

        localStorage.setItem('data', JSON.stringify(data)); // data is assumed to be an array or an object

        $.ajax({
             type: "POST",
             url: "/recipes/createRecipe",
             data: $(this).serialize(), // serializes form input
             success: function(data){
                  localStorage.removeItem('data') // clear the data from localStorage as it won't be necessary again
                  // do another thing 

             },
             error: function(data){
               
                // throw or return error message
             }
        });
    });

    if (localStorage.getItem('data') !== null) { // The getItem(key) method must return the current value associated with the given key. If the given key does not exist in the list associated with the object then this method must return null.
        const data = JSON.parse(localStorage.getItem('data')); // parse the retrieve JSON object from localStorage. Data should be exactly the way you put it earlier
  
       $('#recipeNameInput').val(data.title); // grab the title form input and populate it with the data.title value.
       $('#imageNameInput').val(data.image);
       $('#recipeDescriptionInput').val(data.description);
       $('#ingredientInput').val(data.ingredients);
       $('#directionInput').val(data.directions);
    }
});