由于最近在调试新的应用程序,程序中涉及到http的跨域问题,ajax的示例脚本如下:
$.ajax({ type: methodType, url: urlAddress, async:asyncType, data:postdata, dataType: ajaxDataType, xhrFields:{withCredentials: true}, crossDomain:true, contentType:contType, beforeSend:function() { funObj.ajaxBefore && funObj.ajaxBefore(); }, success:function(data){ funObj.ajaxSuccess(data,funObj); }, complete:function(){ funObj.ajaxComplete && funObj.ajaxComplete(); }, error:function(xhr, textStatus, errorThrown) { if(xhr.status == 403) { Materialize.toast("你当前的会话已失效或无权访问该地址!",MSG_TIMEOUT); } else { if(funObj.ajaxError) { funObj.ajaxError(); } else { ajaxError(); } } return; } });
其中:xhrFields:{withCredentials: true} 表示将本次请求附加cookie信息; crossDomain:true 表示允许脚本跨域请求; 后台的服务器端的web.xml增加一个filter配置如下:<filter> <filter-name>CorsFilter</filter-name> <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class> <init-param> <param-name>cors.allowOrigin</param-name> <param-value>*</param-value> </init-param> <init-param> <param-name>cors.supportedMethods</param-name> <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value> </init-param> <init-param> <param-name>cors.supportedHeaders</param-name> <param-value>*</param-value> </init-param> <init-param> <param-name>cors.exposedHeaders</param-name> <param-value>X-Test-1,X-Test-2</param-value> </init-param> <init-param> <param-name>cors.supportsCredentials</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>cors.maxAge</param-name> <param-value>3600</param-value> </init-param> </filter><filter-mapping> <filter-name>CorsFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>上面需要注意的是:filter-mapping需要是排在第一个的filter,如果不是第一个在其它filter做的一些鉴权会有问题,切记。