1.前段页面效果
2.前段页面代码
<input type="text" id="param1"/> +
<input type="text" id="param2"/> =
<input type="text" id="result"><input type="button" value="get content from server" id="button1">
3.服务器端代码
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int param1 = Integer.parseInt(request.getParameter("param1"));
int param2 = Integer.parseInt(request.getParameter("param2"));
response.setHeader("pragma", "no-cache");
response.setHeader("cache-control", "no-cache");
PrintWriter out = response.getWriter();
out.println(String.valueOf(param1+param2));
out.flush();
}
4.前段页面脚本处理代码
<script type="text/javascript">
$(function(){
$("#button1").click(function(){
$.ajax({ //no need to judge the browser type
type: "POST", //类型
url: "MyServlet", //请求访问的servlet
dataType: "html",
data: {'param1':$("#param1").val(),'param2':$("#param2").val()}, //传递的参数
success: function(returnedData){ //成功返回的回调函数
$("#result").val(returnedData);
}
});
});
});
</script>
<script type="text/javascript">
$(function(){
$("#button1").click(function(){
$.ajax({ //no need to judge the browser type
type: "POST", //类型
url: "MyServlet", //请求访问的servlet
dataType: "html",
data: {'param1':$("#param1").val(),'param2':$("#param2").val()}, //传递的参数
success: function(returnedData){ //成功返回的回调函数
$("#result").val(returnedData);
}
});
});
});
</script>
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int param1 = Integer.parseInt(request.getParameter("param1"));
int param2 = Integer.parseInt(request.getParameter("param2"));
response.setHeader("pragma", "no-cache");
response.setHeader("cache-control", "no-cache");
PrintWriter out = response.getWriter();
out.println(String.valueOf(param1+param2));
out.flush();
}