jsp中的demo
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>jQ ajax</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.min.js"></script>
<script>
$(function(){
$("#but").click(function(){
var sdata=$("form").serialize(); //把表单序列化
var ajaxurl="aja.do?"+sdata;
$.get(ajaxurl,function(data){ //ajax的get方法
$("input[name=res]").val(data);
});
});
});
</script>
</head>
<body>
<form name="form1">
<input type="text" name="num1"/>+
<input type="text" name="num2"/>=
<input type="text" name="res"/>
<input type="button" id="but" />
</form>
</body>
</html>
java
package ajaxApply;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="aa",urlPatterns="/aja.do")
public class ajaxApply extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String n1=req.getParameter("num1");
String n2=req.getParameter("num2");
Integer in1 = new Integer(n1); //转换类型
Integer in2 = new Integer(n2);
int res = in1+in2;
PrintWriter pw=resp.getWriter();
pw.print(res);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req,resp);
}
}