Jquery:
$.get(url,data,callback,type);
Url:服务器的路径
Data: 请求参数
Callback: 回调函数
Type: 响应数据的类型。 (html, json)
$.post(url,data,callback,type);
$.ajax({
Url:
Data:
Type:
Success:
Error:
Async:
dataType:
});
Servlet:
Out.print();//响应的数据 文本 对象 借助gson jar包。把Java对象转化为json对象.
Controller: springmvc。
- 加入jackson的jar包. springmvc。
- 在响应的方法上加上@ResponseBody :把java对象转化为json对象。
- 方法的返回值可以是对象集合字符串。
AjaxController.java
1 package com.zhiyou100.wc.controllter; 2 3 import java.text.ParseException; 4 import java.text.SimpleDateFormat; 5 import java.util.ArrayList; 6 import java.util.List; 7 8 import org.springframework.stereotype.Controller; 9 import org.springframework.web.bind.annotation.RequestMapping; 10 import org.springframework.web.bind.annotation.ResponseBody; 11 12 import com.zhiyou100.wc.bean.Users; 13 14 @Controller 15 @RequestMapping("ajax") 16 public class AjaxController { 17 18 @RequestMapping("Ajax1") 19 @ResponseBody //1.把hello作为内容响应给客户了 20 public String ajax1(String name) { 21 System.out.println(name); 22 return "你好";//表达的是把这个hello作为内容返回给回调函数。out.print("hello"); 23 } 24 25 @RequestMapping("Ajax2") 26 @ResponseBody //2.把java对象转化为json对象,需要使用jackson的jar包 27 public Users ajax2(String name) throws ParseException { 28 Users user=new Users("wangchen","122","man",18,"nanjing","1233225455",new SimpleDateFormat("yyyy-MM-dd").parse("2019-08-21")); 29 return user; 30 } 31 @RequestMapping("Ajax3") 32 @ResponseBody //2.把java对象转化为json对象,需要使用jackson的jar包 33 public List<Users> ajax3(String name) throws ParseException { 34 Users user1=new Users("wangchen1","122","man",18,"nanjing","1233225455",new SimpleDateFormat("yyyy-MM-dd").parse("2019-08-21")); 35 Users user2=new Users("wangchen2","122","man",18,"nanjing","1233225455",new SimpleDateFormat("yyyy-MM-dd").parse("2019-08-21")); 36 Users user3=new Users("wangchen3","122","man",18,"nanjing","1233225455",new SimpleDateFormat("yyyy-MM-dd").parse("2019-08-21")); 37 Users user4=new Users("wangchen4","122","man",18,"nanjing","1233225455",new SimpleDateFormat("yyyy-MM-dd").parse("2019-08-21")); 38 List<Users> users=new ArrayList<>(); 39 users.add(user1); 40 users.add(user2); 41 users.add(user3); 42 users.add(user4); 43 return users; 44 } 45 }
ajax.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 <script type="text/javascript" src="/Springmvc-0903/js/jquery-3.2.1.min.js"></script> 9 <script type="text/javascript"> 10 $.post("ajax/Ajax1",{"name":"zs"},function(data){ 11 alert(data); 12 13 }); 14 15 $.post("ajax/Ajax2",{"name":"zs"},function(data){ 16 alert(data.uname); 17 18 }); 19 20 $.post("ajax/Ajax3",{"name":"zs"},function(data){ 21 $.each(data,function(i,e){ 22 alert(e.uname); 23 }); 24 25 }); 26 27 28 </script> 29 </head> 30 <body> 31 32 </body> 33 </html>