2、jQuery的Ajax简单示例
一、创建一个JavaWEBProject
二、创建一个Servlet(下面的例子中用到了Json--第32行,Json的作用是将一个Object类转换为特定格式的字符串,如果不用Json直接返回字符串也行)。
1 package com.czj.ajax; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.util.HashMap; 6 import java.util.Map; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 public class AJAXServlet extends HttpServlet { 14 public void doGet(HttpServletRequest request, HttpServletResponse response) 15 throws ServletException, IOException { 16 } 17 18 public void doPost(HttpServletRequest request, HttpServletResponse response) 19 throws ServletException, IOException { 20 boolean flag = false; 21 System.out.println(request.getParameter("userName")); 22 if("陈泽俊".equals(request.getParameter("userName"))) 23 flag = true;//登陆成功标志 24 System.out.println(request.getParameter("password")); 25 response.setContentType("text/html;charset=utf-8"); 26 PrintWriter out = response.getWriter(); 27 28 Map<String, Object> map = new HashMap<String, Object>(); 29 map.put("userName","陈泽俊"); 30 map.put("password", "123456"); 31 map.put("flag", flag);//登陆失败 32 out.print(MyJson.objectToJson(map));//返回登录信息 33 out.flush(); 34 out.close(); 35 } 36 }
上面的32行有一个MyJson的类,其代码如下:
【注意】用Json的时候要先引入Json所需的基本jar包
1 package com.czj.ajax; 2 3 4 import net.sf.json.JSONArray; 5 6 public class MyJson { 7 public static String objectToJson(Object resultobj){ 8 if (resultobj != null) { 9 JSONArray obj = JSONArray.fromObject(resultobj); 10 return (obj.toString()); 11 } 12 return ""; 13 } 14 }
三、写相应的jsp页面
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <script type="text/javascript" src="Jscript/jquery-3.1.1.min.js"></script> 11 <script type="text/javascript"> 12 13 $(document).ready(function(){ 14 $("button").click(function(){ 15 $.ajax({ 16 type:"post",//提交方式 17 url:"${pageContext.request.contextPath}/servlet/AJAXServlet.do", 18 data:{ 19 userName: $("#userName").val() , 20 password: $("#password").val() 21 }, //data中的类容会自动的添加到url后面 22 dataType: "json", //1、text 2、jsonscript 3、html 4、xml 5、String 23 success:function(data){ //这个function里面的参数可以随便写 24 if(data[0].flag == true){ 25 alert("登陆成功!"); 26 }else{ 27 alert("登陆失败!"); 28 } 29 } 30 }); 31 }); 32 }); 33 </script> 34 </head> 35 36 <body> 37 <div> 38 <div> 39 <ul> 40 <li>用户名:</li> 41 <li><input id="userName" name="userName" type="text" /></li> 42 </ul> 43 </div> 44 <div> 45 <ul> 46 <li>密码:</li> 47 <li><input id="password" name="password" type="password"/></li> 48 </ul> 49 </div> 50 <div> 51 <ul> 52 <li><button>登陆</button></li> 53 </ul> 54 </div> 55 </div> 56 </body> 57 </html>