AJAX 请求网络

一、引入jquery文件

二、请求方式
$.ajax({
    type: "GET",
    data: {},
    dataType: "JSON",
    contentType: "application/json;charset=UTF-8",
    async: false,
    url: "${ctx}/system/menu",
    success: function (data) {
        var html = "";
        html += "
    "; for (var i = 0; i < data.length; i++) { // 一级菜单 html += "
  • " + "" + data[i].name + ""; html += ""; html += "
  • "; } html += "
"; $("#menu").html(html); }, error:(data) => { 服务器没有返回数据,方法返回值void,抛异常等 } });
三、解决跨域访问
crossDomain: true; -> 前端ajax请求属性
response.setHeader("Access-Control-Allow-Origin", "*"); -> 后端设置
四、请求时携带cookie
xhrFields: {
    withCredentials: true -> 前端ajax请求属性
}

String origin = request.getHeader("Origin"); -> 后端设置
if (StringUtils.isEmpty(origin)) {
    origin = request.getHeader("Referer");
}
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Credentials", "true");

if (RequestMethod.OPTIONS.toString().equals(request.getMethod())) {
    String allowMethod = request.getHeader("Access-Control-Request-Method");
    String allowHeaders = request.getHeader("Access-Control-Request-Headers");
    response.setHeader("Access-Control-Max-Age", "86400"); -> 浏览器缓存预检请求结果时间,单位:秒
    response.setHeader("Access-Control-Allow-Methods", allowMethod); ->允许浏览器在预检请求成功之后发送的实际请求方法名
    response.setHeader("Access-Control-Allow-Headers", allowHeaders); ->允许浏览器发送的请求消息头
}

检测请求来源为ajax,如果ajax设置了跨域属性crossDomain,请求头将会消失(无法检测)
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
  String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
  response.setHeader("REDIRECT", "REDIRECT");
  response.setHeader("CONTENTPATH", url + "/login.html");
  response.setStatus(HttpServletResponse.SC_FORBIDDEN);
  } else {
    String url = request.getContextPath() + "/login.html";
    response.sendRedirect(url);
    }

多个异步任务执行完成后再执行下面操作
$.when(ajax1,ajax2,ajax3).done(function(){
    完成时回调
}).fail(function () {
    失败时回调
});

$.when(ajax1,ajax2,ajax3).then(done(),fail());
五、AJAX跳转页面
window.location.href = url + "/login.html"; -> 当前页面路径跳转某个页面路径
window.location.replace(document.referrer); -> 跳转到上一个页面并刷新
window.location.reload(); -> 重新加载当前页
history.back(); -> 浏览器点击后退按钮效果
history.forward(); -> 浏览器点击前进按钮效果
history.go(index); -> 综合前进后退效果,正数向前,负数想后
六、跳转到上一个页面
function historyGoBack() {
    if ((navigator.userAgent.indexOf('MSIE') >= 0) && (navigator.userAgent.indexOf('Opera') < 0)) { // IE
        if (history.length > 0) {
            window.location.replace(document.referrer);
        } else {
            window.location.href = url+"/main.html";
        }
    } else { //非IE浏览器
        if (navigator.userAgent.indexOf('Firefox') >= 0 ||
            navigator.userAgent.indexOf('Opera') >= 0 ||
            navigator.userAgent.indexOf('Safari') >= 0 ||
            navigator.userAgent.indexOf('Chrome') >= 0 ||
            navigator.userAgent.indexOf('WebKit') >= 0) {

            if (window.history.length > 1) {
                if (document.referrer.indexOf("/register.html") > -1) {
                    window.location.href = url+"/main.html";
                } else {
                    window.location.replace(document.referrer);
                }
            } else {
                 window.location.href= url+"/main.html";
            }
        } else { //未知的浏览器
            window.location.replace(document.referrer);
        }
    }
}

通过window.location.href获取当前页面路径,以参数的方式传给后台方法,
登录成功后,在控制器中通过重定向跳转到该参数路径的页面。

注意事项:在浏览器访问的地址和在ajax中的访问地址必须完全一样,否则会出现获取不到cookie的结果。ajax请求里面嵌套ajax请求,请求方式需要设置为同步,否则在ajax结果回调前,已经执行下面的代码。

七、获取URL的参数
var parseUrl = function () { -> 普通URL
    var searchHref = window.location.search.replace('?', '');
    var params = searchHref.split('&');
    var returnParam = {};
    params.forEach(function(param) {
      var paramSplit = param.split('=');
      returnParam[paramSplit[0]] = paramSplit[1];
    });
    return returnParam;
}

var parseUrl = function() { -> 特殊符号URL
    var index = window.location.href.indexOf('?');
    var href = window.location.href.substr((index+1));
    var params = href.split('&');
    var returnParam = {};
    params.forEach(function(param) {
        var paramSplit = param.split('=');
        returnParam[paramSplit[0]] = paramSplit[1];
    });
    return returnParam;
}

你可能感兴趣的:(AJAX 请求网络)