使用ajax从表单获取数据?

时间:2017-07-21 13:51:33

标签: javascript jquery ajax

我正在尝试使用jquery从html表单中获取数据。我尝试了以下但由于某种原因,当我尝试在控制台中记录数据时,我一直都是null。我能做错什么?我想将以json格式从我的表单中捕获的数据发送到我的servlet。感谢

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<style>
.vertical-menu {
    width: 200px;
}

.vertical-menu a {
    background-color: #eee;
    color: black;
    display: block;
    padding: 12px;
    text-decoration: none;
}

.vertical-menu a:hover {
    background-color: #ccc;
}

.vertical-menu a.active {
    background-color: #4CAF50;
    color: white;
}
</style>
</head>
<body>

<form id="register">
<div class="vertical-menu">

</div>
 API Name:<br>
  <input type="text" id = "apiname" name="apiname">
   API ENDPOINT:<br>
  <input type="text" id ="apiendpoint" name="apiendpoint">
  <br>
  API VERSION:<br>
  <input type="text" id="apiversion" name="apiversion">
   ACCESSIBLE:<br>
  <input type="checkbox" name="source" value="internet"> Internet<br>
    <input type="checkbox" name="source" value="vpn"> VPN<br>


  <br>
    <input type="submit" id="check" name="check" value="Insert">

</form> 
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
      event.preventDefault();
      var d = $('register').serialize();
      console.log("d",d);
     $.ajax({
            type: "POST",
            url: "HomeServlet",
            dataType: "text",
            contentType: "application/json",
            data:d,
            success: function(data){
                console.log(data);
            },
            error:function(){
                console.log("error");
            },

        });
});

</script>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

你忘了给出合适的选择器: register是表单的ID;

$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
      event.preventDefault();
      var d = $('#register').serialize(); // You had missed # here.
      console.log("d",d);
     $.ajax({
            type: "POST",
            url: "HomeServlet",
            dataType: "text",
            contentType: "application/json",
            data:d,
            success: function(data){
                console.log(data);
            },
            error:function(){
                console.log("error");
            },

        });
});

答案 1 :(得分:0)

q=name_spell:(nike%20shoes)

我认为这是实现您所需要的正确方法。不要忘记将event参数添加到回调函数中。