gpt4 book ai didi

javascript - 使用ajax从表单获取数据?

转载 作者:行者123 更新时间:2023-11-30 21:20:28 25 4
gpt4 key购买 nike

我正在尝试使用 jquery 从 html 表单中获取数据。我尝试了以下操作,但由于某种原因,当我尝试在控制台中记录数据时,我一直为空。我做错了什么?我想以 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>

最佳答案

您忘记提供正确的选择器: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");
},

});
});

关于javascript - 使用ajax从表单获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45239477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com