从HTML表单中获取字段,并使用JQuery/Javascript将它们发送给Servlet的最佳方法是什么?

What is the best way to get the fields from a HTML form, and send them to a Servlet using JQuery/Javascript?

本文关键字:Servlet 是什么 方法 最佳 Javascript 获取 字段 表单 HTML JQuery      更新时间:2023-09-26

使用jQuery,我找到了这样的解决方案:

$("#submit").click(function () {
    alert($('form1').serialize());
    $.post("submitForm", $("form1").serialize(), function (result) {
        if (result == "success") {
            alert("Record added!");
        } else {
            alert("Could not add Record!");
        }
    });
});

这是我上面描述的方法的完整HTML,我试图找到从HTML表单中获取数据并将其发送到servlet"submitForm"的最佳方法。

<html>
 <head>
<title>myForm</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
    $("#submit").click(function () {
    alert($('form1').serialize());
    $.post("submitForm", $("wmform_174835").serialize(), function (result) {
        if (result == "success") {
            alert("Record added!");
        } else {
            alert("Could not add Record!");
        }
    });
});
</script>
</head>
<body>
<a href="submitForm">MyForm</a>
<form action="submitForm" method="POST" id="form1">
    <input type="text" value="12" name="ID"/>
    <input type="text" value="NameThatComesFirst" name="FirstName"/>
    <input type="text" value="NameThatComesLast" name="LastName"/>
    <input type=submit id="submit" value="submit"/>
</form>
</body>
</html> 

试试这个-

   $(document).ready(function(){
     $("#submit").click(function () 
       var data = $('#form1').serialize();
       alert(data);
       $.post("submitForm", data, function (result) {
            if (result == "success") {
              alert("Record added!");
            } else {
                alert("Could not add Record!");
            }
       });
    });
   });