1、建立一個JavaWEBProjectjavascript
2、建立一個Servlet(下面的例子中用到了Json--第32行,Json的做用是將一個Object類轉換爲特定格式的字符串,若是不用Json直接返回字符串也行)。html
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的類,其代碼以下:java
【注意】用Json的時候要先引入Json所需的基本jar包jquery
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 }
3、寫相應的jsp頁面ajax
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", //一、text 二、jsonscript 三、html 四、xml 五、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>