JQuery 动态加载CSS

来源:互联网 发布:his医疗软件 编辑:程序博客网 时间:2024/06/06 05:59

1. 刚进入页面时,使用 $(document).ready

$(document).ready(function() {$.ajax({type : "POST",url : "loginController.do?getCssPath",dataType : "json",success : function(data) {if(data.obj != null){loadStyles(data.obj);}}});});

2. 在url 属性中,调用controller中params为"getCssPath"的方法,返回JSON数据。

@RequestMapping(params = "getCssPath")@ResponseBodypublic AjaxJson getCssPath(ModelMap modelMap,HttpServletRequest request,HttpServletResponse response) {AjaxJson j = new AjaxJson();SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式String path = null;try {JformThemeInfoEntity jformThemeInfoEntity = systemService.findUniqueByProperty(JformThemeInfoEntity.class,"themeDate", df.parse(df.format(new Date())));if(jformThemeInfoEntity != null){path = jformThemeInfoEntity.getPath();j.setObj(path);}} catch (Exception e) {e.printStackTrace();log.error(e.getMessage());}return j;}

3. 成功后,调用JS function的success属性,调用 loadStyles() JS function。

function loadStyles(url) {var link = document.createElement("link");link.type = "text/css";link.rel = "stylesheet";link.href = url;document.getElementsByTagName("head")[0].appendChild(link);}

PS:如果没有走到java方法中,那么可能是因为拦截器拦截了,所以我们需要在xml配置中配置。

<mvc:interceptor><mvc:mapping path="/**" /><bean class="org.jeecgframework.core.interceptors.AuthInterceptor"><property name="excludeUrls"><list><!-- 加载主题样式 --><value>loginController.do?getCssPath</value></list></property></bean></mvc:interceptor>


原创粉丝点击