Ajax
…
(暂时不想更…ಠ╭╮ಠ)
1.Ajax概念
2.Ajax组成/作用
3.Ajax在JS/JQ中的使用
4.Ajax跨域服务
ajax默认关闭跨域服务功能,有两种方案可以开启,一种是jsonp和callback前后端都修改
方案一(处理前后端)
前端
1 2 3 4 5 6 7
| .ajax({ type:"get", //请求方式 async:true, //是否异步 url:"http://www.domain.net/url", dataType:"jsonp", //跨域json请求一定是jsonp,js默认发送callback(自动生成,也可指定的字符串) data:{"query":"civilnews"}, ...
|
后端
1 2 3 4 5 6 7 8 9
| @RequestMapping("info.html") @ResponseBody public String check(String callback, HttpServletRequest request) { //从cookie中获取票据 String token = CookieUtils.getCookieValue(request, TOKEN_KEY); //查询用户信息 TravelResult result = userService.getUserByToken(token); return callback + "(" + JsonUtil.getJSON(result) + ")"; //返回callback拼接Json }
|
方案二(后端拦截器处理)
粗粒度拦截
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| package com.jgonet.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; public class HeaderFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) resp; response.setHeader("Access-Control-Allow-Origin", "*"); //解决跨域访问报错 response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); //设置过期时间 response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization"); response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // 支持HTTP 1.1. response.setHeader("Pragma", "no-cache"); // 支持HTTP 1.0. response.setHeader("Expires", "0"); chain.doFilter(request, resp); } public void init(FilterConfig filterConfig) {} public void destroy() {}
|
web.xml
1 2 3 4 5 6 7 8
| <filter> <filter-name>HeaderFilter</filter-name> <filter-class>com.jgonet.filter.HeaderFilter</filter-class><!--你过滤器的包 --> </filter> <filter-mapping> <filter-name>HeaderFilter</filter-name> <url-pattern>/*</url-pattern><!-- 你开放的接口前缀 --> </filter-mapping>
|
方案三(后端方法处理)
精确细粒度拦截时使用,普通拦截使用拦截即可
1 2 3
| 需要的方法设置响应头即可 response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
|
5.Ajax结合单点登录流程
SSO(single sign-on)
- 登录查询账号密码,返回Token
- Token返回时存进Redis中一份(以JSESSION+xxx+token为Key, JsonUtil.getJSON(user)为value)
- 将Token放进Cookie中,用户请求服务器时,服务器会将Cookie中的信息取出作为Key和Redis中的Key对比,来判断是否登录,从而返回前端状态即可
6.Ajax常见问题