Ajax主要来实现局部刷新的。
这是一个项目:
AjaxTest.java(Servlet)
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * Created by Administrator on 2016/12/1. */ public class AjaxTest extends HttpServlet { @Override public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException { PrintWriter out = resp.getWriter(); String name= req.getParameter("name"); if(name==null||name.equals("")) { out.println("please input username"); } else if(name.equals("wh")){ out.println("welcome "+name); }else{ out.println("the user doesn't esist!"); } } @Override public void doPost(HttpServletRequest req,IOException { doGet(req,resp); } }ajax.html(填写数据,展示页面)
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="jquery-3.1.1.js"></script> <script type="text/javascript" src="verify.js"></script> </head> <body> 使用ajax技术处理 <input type=text" id="input" name="name" /> <input type="button" value="校验" onclick="verify()"/> <div id="result"></div> </body> </html>verify.js
function verify() { var input = $("#input"); var username = input.val(); $.get("AjaxTest?name="+username,null,callback); } function callback(data){ var res=$("#result"); res.html(data); }每点击一下按钮,就会调用verify函数,从Servlet调出数据,显示在div里。