【发布时间】:2015-09-19 01:01:42
【问题描述】:
我是 servlet 的新手,我能够从 servlet 获取数据,但无法向其发送数据,我想在不使用提交表单的情况下执行此操作,请给我一些帮助
单击按钮后,它将转到 servlet 并返回文本,但不返回发送给它的值
这是我的 index.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 4112686</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('#somebutton').click(function() {
$.get('GetUserServlet', function(responseText) {
$('#somediv').text(responseText);
});
});
});
$("#somebutton").click(function(){
$.ajax
(
{
url:'GetUserServlet',
data:{name:'abc'},
type:'get',
cache:false,
success:function(data){alert(data);},
error:function(){alert('error');}
}
);
}
);
</script>
</head>
<body>
<button id="somebutton" onclick="showHint('GetUserServlet.java', 'travis');">press here</button>
<div id="somediv"></div>
</body>
这是我的 servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String text = "Update Sucessful";
String name = request.getParameter("name");
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write( name + text); // Write response body.
【问题讨论】:
-
以前没用过,但我愿意尝试
-
再看一遍,你已经是 :) 那些 $ 是 jQuery 调用。所以你已经在使用 jQuery.ajax() 函数了。给我一些来看看我现有的 ajax/servlet 交互以记住它是如何工作的:)