JavaScript获取浏览器地址栏参数JS

代码如下调用即可function getUrlSearch(name) {    // 未传参,返回空    if (!name) return null;    // 查询参数:先通过search取值,如果取不到就通过hash来取    var after = window.location.search;    after = after.substr(1) || window.location.hash.split('?')[1];    // 地址栏URL没有查询参数,返回空    if (!after) return null;    // 如果查询参数中没有"name",返回空    if (after.indexOf(name) === -1) return null;    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');    // 当地址栏参数存在中文时,需要解码,不然会乱码    var r = decodeURI(after).match(reg);    // 如果url中"name"没有值,返回空    if (!r) return null;    return r[2];}调用示例:var qq = getUrlSearch('qq')

浏览器同源策略 JS跨域解决方案Spring中CORS

CORS 是一个 W3C 标准,全称是"跨域资源共享"(Cross-origin resource sharing)。CORS 需要浏览器和服务器同时支持。目前,所有浏览器都支持该功能,IE 浏览器不能低于 IE10。它允许浏览器向跨源服务器,发出 XMLHttpRequest 请求,从而克服了 AJAX 只能同源 使用的限制。整个 CORS 通信过程,都是浏览器自动完成,不需要用户参与。对于开发者来 说,CORS 通信与同源的 AJAX 通信没有差别,代码完全一样。浏览器一旦发现 AJAX 请求跨 源,就会自动添加一些附加的头信息,有时还会多出一次附加的请求,但用户不会有感觉。 因此,实现 CORS 通信的关键是服务器。只要服务器实现了 CORS 接口,就可以跨源通信。解决跨域其实很简单,以下示例在后端Controller层:首先在类中注入response@Autowiredprivate HttpServletResponse response;在需要跨域的方法里加上        response.setHeader("Access-Control-Allow-Origin", "http://cway.top");//可以访问的域(当此方法不需要操作cookie则无需下面一行)可以用*通配所有地址        response.setHeader("Access-Control-Allow-Credentials", "true");//如果操作cookie,必须加上这句话,操作cookie上面不能用通配符 必须固定网址由于操作cookie,需要改下前端代码,在请求网址后面加 ,{'withCredentials':true}$http.get('http://cway.top/?page='+$scope.num,{'withCredentials':true}).success( function(response){ ....... });当然在springMVC4.2及以后版本添加了Cros注解,可以省去上述后端代码直接写注解@CrossOrigin(origins="http://cway.top",allowCredentials="true")其中allowCredentials="true缺省值就是true,因此也可以省略不写,该注解可以加载方法上或类上,可以使用通配符例如*Spring MVC CORS 使用WebMvcConfigurerAdapter要为整个应用程序启用CORS,请使用WebMvcConfigurerAdapter 添加 CorsRegistry@Configuration@EnableWebMvcpublic class CorsConfiguration extends WebMvcConfigurerAdapter{    @Override    public void addCorsMappings(CorsRegistry registry) {        registry.addMapping("/**")                .allowedMethods("GET", "POST");    }}Spring Boot CORS 使用WebMvcConfigurer配置在spring boot应用程序中,建议只声明一个WebMvcConfigurer bean。@Configurationpublic class CorsConfiguration{    @Bean    public WebMvcConfigurer corsConfigurer()    {        return new WebMvcConfigurerAdapter() {            @Override            public void addCorsMappings(CorsRegistry registry) {                registry.addMapping("/**");            }        };    }}或者直接注入CorsConfiguration:@Configurationpublic class CORSConfiguration {    private CorsConfiguration buildConfig() {        CorsConfiguration corsConfiguration = new CorsConfiguration();        //允许任何域名访问        corsConfiguration.addAllowedOrigin("*");        //允许任何header访问        corsConfiguration.addAllowedHeader("*");        //允许任何方法访问        corsConfiguration.addAllowedMethod("*");        // 允许cookies跨域        corsConfiguration.setAllowCredentials(true);        // 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了        corsConfiguration.setMaxAge(18000L);        return corsConfiguration;    }    @Bean    public CorsFilter corsFilter() {        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();        source.registerCorsConfiguration("/**", buildConfig());        return new CorsFilter(source);    }}CORS 使用Spring Security配置要通过Spring安全性启用CORS支持,请配置CorsConfigurationSource bean并使用HttpSecurity.cors() 配置@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {     @Override    protected void configure(HttpSecurity http) throws Exception {        http.cors().and()            //other config    }     @Bean    CorsConfigurationSource corsConfigurationSource()    {        CorsConfiguration configuration = new CorsConfiguration();        configuration.setAllowedOrigins(Arrays.asList("https://example.com"));        configuration.setAllowedMethods(Arrays.asList("GET","POST"));        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();        source.registerCorsConfiguration("/**", configuration);        return source;    }}部分参考来源:http://www.leftso.com/blog/303

AngularJS入门及示例

AngularJS 诞生于 2009 年,由 Misko Hevery 等人创建,后为 Google 所收购。是一款优 秀的前端 JS 框架,已经被用于 Google 的多款产品当中。AngularJS 有着诸多特性,最为核心 的是:MVC、模块化、自动化双向数据绑定、依赖注入等等。双向绑定(同变量值同步变化):<html><head><title>入门小 Demo-1</title><script src="angular.min.js"></script></head><!-- ng-init初始化 --><body ng-app ng-init="myname='蔡徐坤'"> <!-- {{}}变量表达式调用 -->{{100+100}}<!-- ng-model变量绑定 双向绑定 即下面同变量名数值都一样 -->请输入你的姓名:<input ng-model="myname">   <input ng-model="myname"><br>{{myname}},你好</body></html>控制器controller与事件:<html> <head> <title>控制器</title> <script src="angular.min.js"></script> <script>  var app = angular.module('myApp', []); //定义了一个名叫 myApp 的模块 []写引入其他模块的名字 //定义控制器 $scope作用域 控制层与视图层的数据桥梁 app.controller('myController', function($scope) { $scope.add = function() { // 获取视图层的变量 转换成int 否则+会作为拼接字符串连接符 return parseInt($scope.x) + parseInt($scope.y); } }); </script> </head> <!-- body绑定模块与控制器 --> <body ng-app="myApp" ng-controller="myController"> x:<input ng-model="x"> y:<input ng-model="y"> 运算结果:{{add()}} </body></html>ng-click事件与ng-repeat循环数组与对象数组:<html> <head> <title>事件指令</title> <script src="angular.min.js"></script> <script> var app = angular.module('myApp', []); //定义了一个叫 myApp 的模块 //定义控制器 app.controller('myController', function($scope) { $scope.add = function() { $scope.z = parseInt($scope.x) + parseInt($scope.y); } $scope.list = [100, 200, 300]; //定义数组 /* 循环对象定义 */ $scope.alist = [{ name: '张三', shuxue: 100 }, { name: '李四', shuxue: 88 }]; //定义数组 }); </script> </head> <body ng-app="myApp" ng-controller="myController"> x:<input ng-model="x"> y:<input ng-model="y"> <!-- ng-click单击事件 --> <button ng-click="add()">计算</button> 结果:{{z}} <!-- 循环数组 ng-repeat = 变量 in 数组 --> <table> <tr ng-repeat="a in list"> <td>{{a}}</td> </tr> </table> <!-- 循环对象 类似Java中用点调用对象属性--> <table> <tr ng-repeat="a in alist"> <td>{{a.name}}</td><td>{{a.shuxue}}</td> </tr> </table> </body></html>$http内置服务:<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title>内置服务</title> <meta charset="utf-8" /> <script src="angular.min.js"></script> <script> var app = angular.module('myApp', []); //定义了一个叫 myApp 的模块 //内置服务$http需要再方法中注入 app.controller('myController', function($scope, $http) { $scope.findAll = function() { // get/post请求 $http.post('data.json').success( function(response) { $scope.list = response; } ); } //由于body调用了该controller 因此必定会调用下行方法而执行上述代码 但放init中就不必担心别的页面每次调用也会执行  // $scope.findAll(); }); </script> </head> <!-- ng-init除了给变量初始化 也可以调用方法 --> <body ng-app="myApp" ng-controller="myController" ng-init="findAll()"> <table> <tr> <td>姓名</td> <td>数学</td> <td>语文</td> </tr> <tr ng-repeat="entity in list"> <td>{{entity.name}}</td> <td>{{entity.shuxue}}</td> <td>{{entity.yuwen}}</td> </tr> </table> </body></html>测试的json数据data.json:[{"name":"张三","shuxue":100,"yuwen":93},{"name":"李四","shuxue":88,"yuwen":87},{"name":"王五","shuxue":77,"yuwen":56},{"name":"赵六","shuxue":67,"yuwen":86}]总结:var app = angular.module('myApp', []) //在js中定义模块app.controller('myController', function($scope) {}    //给模块创建名为myController的控制器$scope //前端与控制层数据的桥梁ng-app="myApp"  //在body标签里绑定模块 将body交给angular管理ng-init="findAll() //初始化变量或者在载入时调用方法 可见第一个demong-controller="myController" //定义控制器{{}}        //调用变量或者运算式<input ng-model="x">    //为标签绑定变量ng-click        //单击事件a in list        //in作为list遍历a.name        //点调用对象属性$http.post('data.json').success(function(response){return response})    //http服务发送请求MVC模式首先在base.js中创建模块,这里命名为appvar app=angular.module('tieba',['pagination']);    //[]内为引入的模块 不需要可留空在服务js中写service:app.service('tiebaService',function($http){   //读取列表数据绑定到表单中   this.findAll=function(){      return $http.get('../tieba/findAll.do');   }});在控制层js中写controller: //控制层app.controller('tiebaController' ,function($scope,$controller   ,tiebaService){ //引用service跟内置服务   $controller('baseController',{$scope:$scope});//继承 baseController    //读取列表数据绑定到表单中   $scope.findAll=function(){      tiebaService.findAll().success(         function(response){            $scope.list=response;         }      );   } });

AnglarJs选择多选框动态求和

只是一个小练习:<!DOCTYPE html><html> <head> <meta charset="utf-8" /> <script src="js/angular.min.js"></script> <script> var app = angular.module('myApp', []); //定义了一个叫 myApp 的模块 //定义控制器 app.controller('myController', function($scope) { $scope.list = [100, 192, 203, 434]; //定义数组 $scope.selectIds=[];//选中的 ID 集合 $scope.getsum=function($event,x){ $scope.sum=0; if($event.target.checked){ $scope.selectIds.push(x); }else{ var idx = $scope.selectIds.indexOf(x);  $scope.selectIds.splice(idx, 1);//删除 } for (var i of $scope.selectIds) { $scope.sum+=i; } }; }); </script> </head> <body ng-app="myApp" ng-controller="myController"> <table> <tr ng-repeat="x in list"> <td>{{x}}<input type="checkbox" ng-click="getsum($event,x)"></td> </tr> </table> 集合:{{selectIds}} 求和:{{sum}} </body></html>前端真难。。