如何提交表格并使数据保留在输入字段中?使用AJAX和Node.js

时间:2018-11-27 00:35:34

标签: javascript jquery html node.js ajax

我正在尝试创建一个用户设置页面,用户在其中输入他/她的信息,单击“保存”,然后该页面将保存数据,而不清除输入的字段或重新加载该页面。我能想到的最好的例子是Udemy上的用户帐户设置页面。

我看过的许多类似问题都在使用php或在div下面的form中渲染数据。我希望数据保留在form inputs中。我正在使用nodejsexpressbodyparser

<form id="updateAccSettings" action="/account" method="POST">       
    <div class="form-group">
         <label for="address">Address* </label>
         <input class="form-control" type="text" name="address" placeholder="Address" required/>
    </div> 

    <div class="form-group">
         <label for="address2">Address 2 </label>
         <input class="form-control" type="text" name="address2" placeholder=""/>
    </div> 

    <div class="form-group">
         <label for="city">City* </label>
         <input class="form-control" type="text" name="city" placeholder="City" />
    </div> 

    <div class="form-group">
         <input type="submit" name="save" class="btn btn-lg btn-primary btn-block" value="Save"/>
    </div>
</form> 

我已经尝试过使用AJAX

$(document).ready(function() {
    $("#updateAccSettings").on("submit", function(e){
        e.preventDefault();
        var details = $("#updateAccSettings").serialize();
        $.post("/account", details, function(data){
            $("#updateAccSettings").html(data);
        });
    });
});

还有这个

$(document).ready(function () {
    $("#updateAccSettings").bind("submit", function(e){
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: "/account",
            data: $("#updateAccSettings").serialize(),
            success: function(){
                alert("You've successfully updated your account settings.")
            }
        });
    });
});

我的app.js有这个

app.post("/account", function(req, res) {
    var address = req.body.address;
    var address2 = req.body.address2;
    var city = req.body.city;
    var updateAccount = {address: address, address2: address2, city: city};
    account.push(updateAccount);
    console.log("Updated data");
    res.redirect("/settings/account");
});

单击save时,我得到一个Cannot read property of 'push' undefined。我尝试删除var addressvar address2等,仅保留console.log,每次单击“保存”时都会记录日志,但不会将数据保留在输入中。我尝试将onsubmit="return false"作为属性添加到form标记上,但是单击保存时console.log无法运行,因此我认为它对数据没有任何作用。

不确定如何从此处继续。我所有其他表单都使用模式或在另一页中呈现结果。

3 个答案:

答案 0 :(得分:0)

收到错误是因为您试图推送到未定义的变量。即在上一节中发布此应用程序的时间。

{
  "query": {
    "match": {
      "class": "10th"
    }
  },
  "aggs": {
    "subjects": {
      "nested": {
        "path": "subject"
      },
      "aggs": {
        "subjects": {
          "terms": {
            "field": "subject.name"
          },
          "aggs": {
            "avg_score": {
              "avg": {
                "field": "subject.marks"
              }
            },
            "weighted_grade": {
              "weighted_avg": {
                "value": {
                  "field": "subject.marks"
                },
                "weight": {
                  "field": "subject.weight"
                }
              }
            }
          }
        }
      }
    }
  },
  "size": 0
}

答案 1 :(得分:0)

一旦您有一个用于帐户的虚拟变量,就可以将返回的json响应发送回前端,以便在表单成功处理程序中读取。 示例代码:(我尚未测试) 后端:

app.post("/account", function(req, res) {
    var account = [];
    var address = req.body.address;
    var address2 = req.body.address2;
    var city = req.body.city;
    var updateAccount = { address, address2, city };
    account.push(updateAccount); // error is being thrown here
    console.log("Updated data");
    res.json(updateAccount);
});

前端:

 $(document).ready(function () {
    $("#updateAccSettings").bind("submit", function(e){
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: "/account",
            data: $("#updateAccSettings").serialize(),
            success: function(data){
                $('#address').value(data.address);
                $('#address2').value(data.address2); 
                $('#city').value(data.city);
            }
        });
    });
});

答案 2 :(得分:0)

您可以为每个表单输入字段提供一个ID(例如,与它们的“ name”属性相同),并在执行ajax请求时分别获取其值,如下所示(这样,您可以在提交表单后重新插入值) ):

HTML

  <form id="updateAccSettings" action="" method="POST">       
        <div class="form-group">
             <label for="address">Address* </label>
             <input class="form-control" type="text" name="address" id="address" placeholder="Address" required/>
        </div> 

        <div class="form-group">
             <label for="address2">Address 2 </label>
             <input class="form-control" type="text" name="address2" id="address2" placeholder=""/>
        </div> 

        <div class="form-group">
             <label for="city">City* </label>
             <input class="form-control" type="text" name="city" id="city" placeholder="City" />
        </div> 

        <div class="form-group">
             <input type="submit" name="save" class="btn btn-lg btn-primary btn-block" value="Save"/>
        </div>
    </form> 

jQuery

$(document).ready(function() {
    $("#updateAccSettings").on("submit", function(e){
        e.preventDefault();
        //get the values of our input fields and store them in local variables
        var address = $("#address").val();
        var address2 = $("#address2").val();
        var city = $("#city").val();

        //prepare the data object to send in the ajax request
        var params = {"address": address, "address2": address2, "city" : city};
        $.ajax({
            type: "POST",
            url: "/account",
            data: JSON.stringify(params),
            dataType: "json",
            success: function(data){
                //the ajax request was successful
                //We can do something with the data we get back here.
                //Also we can reinsert the values (that were submitted) to the form
                $("#address").val(address);
                $("#address2").val(address2);
                $("#city").val(city);     
            },
            error: function(xhr, status, error) {
                //an error occured in the request so handle it here
            }

        });
    });
});