1、通过jQuery发起Ajax请求
1 <script type="text/javascript" 2 src="${pageContext.request.contextPath}/js/jquery.min.js"> 3 4 </script> 5 <script type="text/javascript"> 6 setInterval("AjaxJquery()", 3000); 7 function AjaxJquery() {//通过jQuery发起请求 8 $.ajax({ 9 url : "${pageContext.request.contextPath}/ajax_do", 10 type : "get", 11 error:function(){ 12 alert("请求失败"); 13 }, 14 success : function(msg) { 15 $("#msg").append(msg); 16 } 17 }); 18 } 19 </script>
setInterval(调用的方法,每个多少毫秒发起)
url:发送请求的地址
type:请求方式
cache:缓存(false每次都清空缓存)
error:请求失败
success:请求后回调函数
2、通过原生的XmlHttpRequest发起请求
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <script type="text/javascript"> 11 window.onload = function() {//页面加载完成后再去获取元素 12 document.getElementById("name").onblur = function() {//获取输入框并注册失去焦点事件 13 //获取输入框的值 14 var name = document.getElementById("name").value; 15 if (name.length > 0) {//输入不为空 16 //创建对象 17 var xhr = new XMLHttpRequest(); 18 //建立连接 请求方式 请求地址 请求为异步请求 19 xhr.open('get', 'MyServlet?name=' + name,true); 20 //发起请求 21 xhr.send(); 22 //注册事件 23 xhr.onreadystatechange = function() {//onreadystatechange 状态改变就会调用 24 if (xhr.readyState == 4 && xhr.status == 200) {//成功请求和成功响应 25 //将响应结果更新到界面xhr.responseText是结果 26 document.getElementById("div1").innerHTML = xhr.responseText; 27 } 28 } 29 } 30 } 31 } 32 </script> 33 <form action="MyServlet"> 34 用户名<input type="text" id="name" name="name" /> <input type="submit" 35 value="提交" /> 36 </form> 37 <div id="div1"></div> 38 </body> 39 </html>
服务器端代码:
1 import java.io.IOException; 2 import javax.servlet.ServletException; 3 import javax.servlet.annotation.WebServlet; 4 import javax.servlet.http.HttpServlet; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 8 @WebServlet("/MyServlet") 9 public class MyServlet extends HttpServlet { 10 private static final long serialVersionUID = 1L; 11 12 protected void doGet(HttpServletRequest request, HttpServletResponse response) 13 throws ServletException, IOException { 14 String name = request.getParameter("name");//获取name的值 15 System.out.println(name); 16 response.getWriter().write(name);//将name发送到客户端 17 } 18 19 protected void doPost(HttpServletRequest request, HttpServletResponse response) 20 throws ServletException, IOException { 21 doGet(request, response); 22 } 23 }