1.index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-2.1.0.js"></script>
<script type="text/javascript">
$(function(){
//为输入框绑定事件
$("#btn").click(function(){
//1、点击提交后获得输入框的内容
var name = $("#uname").val();
//AJAX回调(调用后台方法返回数据)
$.get("HelloAjax",{"uname":name},function(data){
alert(data);
})
})
})
</script>
</head>
<body>
<input type="text" id="uname"><input id="btn" type="button" value="提交">
</body>
</html>
2.HelloAjax.java
package web;
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;
//Servlet
@WebServlet("/HelloAjax")
public class HelloAjax extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloAjax() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得输入的内容,从request取数据,通俗说就是从浏览器取数据
String name = request.getParameter("uname");
System.out.println("欢迎:"+name);
PrintWriter out = response.getWriter();//返回的是PrintWriter,这是一个打印输出流。
out.print("this is Ajax");//不仅可以打印输出文本格式的(包括html标签),还可以将一个对象以默认的编码方式转换为二进制字节输出
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}