当前位置 : 主页 > 网络编程 > JavaScript >

js保存数据和js获取数据js日期设置,anguljs 发送请求和保存数据

来源:互联网 收集:自由互联 发布时间:2021-06-30
gistfile1.txt ///////////////////js保存数据和获取数据////////////////////////////////var JobCircle = JobCircle || {};JobCircle.Util = JobCircle.Util || {};JobCircle.Util.Common = JobCircle.Util.Common || {};/** * 将json对象转换为
gistfile1.txt
///////////////////js保存数据和获取数据////////////////////////////////
var JobCircle = JobCircle || {};
JobCircle.Util = JobCircle.Util || {};
JobCircle.Util.Common = JobCircle.Util.Common || {};

/**
 * 将json对象转换为字符串
 * @param {Object} obj
 */
JobCircle.Util.Common.JsonToString = function(obj){
    var THIS = this;
    switch (typeof(obj)) {
        case 'string':
            return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';
        case 'array':
            return '[' + obj.map(JobCircle.Util.Common.JsonToString).join(',') + ']';
        case 'object':
            if (obj instanceof Array) {
                var strArr = [];
                var len = obj.length;
                for (var i = 0; i < len; i++) {
                    strArr.push(JobCircle.Util.Common.JsonToString(obj[i]));
                }
                return '[' + strArr.join(',') + ']';
            }
            else 
                if (obj == null) {
                    return 'null';
                    
                }
                else {
                    var string = [];
                    for (var property in obj) 
                        string.push(JobCircle.Util.Common.JsonToString(property) + ':' + JobCircle.Util.Common.JsonToString(obj[property]));
                    return '{' + string.join(',') + '}';
                }
        case 'number':
            return obj;
        case false:
            return obj;
    }
};
/**
 * 利用Window.name去保存数据
 * @param {Object} name
 * @param {Object} value
 */
JobCircle.Util.Common.setSession = function(name,value){

	var wn = null;
	try{
		//parseJSON是讲字符串转换为json对象
		wn = $.parseJSON(window.name);
		if(wn == null){
			wn = {};
		}
	}catch(e){
		if(!wn)
			wn = {};
	}
	wn[name] = value;
	
	try{
		window.name = JobCircle.Util.Common.JsonToString(wn);
	}catch(ex){
		return null;
	}
	return value;
};

/**
 * 利用window.name去获取数据
 * @param {Object} name
 */
JobCircle.Util.Common.getSession = function(name,isParent){
	var value = null;
	try{
		if(isParent === true ){
			value = $.parseJSON(parent.window.name) || {};
		}else{
			value = $.parseJSON(window.name) || {};
		}
	}catch(e){
		if(name == 'user.id'){
			return null;
		}
		return {};
	}
	return value[name];
}

/**
 * 传入一个字符串,获取出他的长度(中文当作2个长度)
 * @param {Object} str
 */
JobCircle.Util.Common.GetLength = function(str){
	
	if(str == null){
		return 0;
	}else {
		return str.replace(/[^\x00-\xff]/g, '**').length;
	}
};
/**
 * 打印一个对象的所有属性,调试用
 * @param {Object}
 */
JobCircle.Util.Common.printObjetProperty=function(o){
    var s="",count=0;
	$.each( o, function(i, n){
	  s+=i + " : " + n+" , ";
	  if(count%6==0){
	    s+="\n";
	  }
	  count++;
	});
	return s;
}
//格式化日期
  Date.prototype.Format = function (fmt) {
                var o = {
                    "M+": this.getMonth() + 1, //月份
                    "d+": this.getDate(), //日
                    "h+": this.getHours(), //小时
                    "m+": this.getMinutes(), //分
                    "s+": this.getSeconds(), //秒
                    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                    "S": this.getMilliseconds() //毫秒
                };
                if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
                for (var k in o)
                    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                return fmt;
            }
  //使用日期格式化
   $scope.userCreateTime = $scope.token.user.createdts == null ? '' : new Date($scope.token.user.createdts).Format("yyyy-MM-dd hh:mm:ss");

//////////////////angulajs保存数据和获取数据以及发送请求///////////////////////////
angular.module('admin.services', [])
    .factory('adService', function ($http, $cookies) {
        var ad = {};
        ad.ctrl = '/';

        ad.index = function (success, error) {
            var url = this.ctrl + 'demo';
            var data = JSON.stringify({"account": "abc", "password": "123"});
            this.postWithLoading(url, data, success, error);
        };

        ad.success = function () {
            showTip('操作成功');
        };

        ad.getWithCB = function (url, data, success, error) {
            var loading = showLoading();
            $http({
                url: url,
                method: 'GET'
            }).success(function (result, status, headers, config) {
                closeLoading(loading);
                if (result.code == 0) {
                    if(success){
                        success(result);
                    } else {
                        ad.success();
                    }
                } else {
                    if (!result.desc) {
                        result = JSON.parse(result);
                    }
                    if (result.code == -7) {
                        var cb = function () {
                            window.location = '/';
                        };
                        showTipWithCb(res.desc, cb);
                        return;
                    }
                    if (error) {
                        error(result);
                    } else {
                        showTip(result.desc);
                    }
                }
            }).error(function (result, status, headers, config) {
                closeLoading(loading);
                showSysError();

            });
        };

        ad.get = function (url, params, success, error) {
            var loading = showLoading();
            $http({
                url: url,
                params: params,
                method: 'GET'
            }).success(function (result, status, headers, config) {
                closeLoading(loading);
                if (result.code == 0) {
                    success ? success(result) : angular.noop();
                } else {
                    if (!result.desc) {
                        result = JSON.parse(result);
                    }
                    if (result.code == -7) {
                        var cb = function () {
                            window.location = '/';
                        };
                        showTipWithCb(res.desc, cb);
                        return;
                    }
                    if(error){
                        error(result);
                    } else {
                        showTip(result.desc);
                    }
                }
            }).error(function (result, status, headers, config) {
                closeLoading(loading);
                showSysError();
            });
        };

        ad.postWithLoading = function (url, data, success, error) {
            var loading = showLoading();
            $http({
                method: 'POST',
                url: url,
                data: data,
                headers: {'Content-Type': 'application/json'}
            }).success(function (res, status, headers, config) {
                closeLoading(loading);
                if (res.code == 0) {
                    if(success){
                        success(res);
                    } else {
                        ad.success();
                    }
                } else {
                    //未登录
                    if (!res.desc) {
                        res = JSON.parse(res);
                    }
                    if (res.code == -7) {
                        var cb = function () {
                            window.location = '/';
                        };
                        showTipWithCb(res.desc, cb);
                        return;
                    }
                    if (error) {
                        error(res);
                    } else {
                        showTip(res.desc);
                        return;
                    }
                }

            }).error(function () {
                closeLoading(loading);
                showSysError();
            });
        };

        ad.postWithCB = function (url, data, success, error) {
            $http({
                method: 'POST',
                url: url,
                data: data,
                headers: {'Content-Type': 'application/json'}
            }).success(function (res, status, headers, config) {
                if (res.code == 0) {
                    if(success){
                        success(res);
                    } else {
                        ad.success();
                    }
                } else {
                    //未登录
                    //res = JSON.parse(res);
                    if (!res.desc) {
                        res = JSON.parse(res);
                        //"{\"code\":\"-7\",\"desc\":\"尊敬的用户,您没有登录,请先登录\"}"
                        if (res.code == -7) {
                            var cb = function () {
                                window.location = '/';
                            };
                            showTipWithCb(res.desc, cb);
                            return;
                        }
                    }
                    if (error) {
                        error(res);
                    } else {
                        showTip(res.desc);
                    }
                }

            }).error(function () {
                showSysError();
            });
        };
        return ad;
    })
    .factory('locals', ['$window', function ($window) {
        return {        //存储单个属性
            set: function (key, value) {
                // $window.localStorage[key] = value;
                sessionStorage.setItem(key,value);
            },        //读取单个属性
            get: function (key, defaultValue) {
                //return $window.localStorage[key] || defaultValue;
                return sessionStorage.getItem(key) || defaultValue;
            },        //存储对象,以JSON格式存储
            setObject: function (key, value) {
                sessionStorage.setItem(key,JSON.stringify(value));
                //$window.localStorage[key] = JSON.stringify(value);//将对象以字符串保存
            },        //读取对象
            getObject: function (key) {
                return JSON.parse(sessionStorage.getItem(key) || '{}')
                //return JSON.parse($window.localStorage[key] || '{}');//获取字符串并解析成对象
            }

        }
    }]);
//使用
angular.module('admin.login.controllers', [])
    /*登录*/
    .controller('login-ctrl', ['$scope', 'adService', '$location', '$rootScope','locals',
        function ($scope, adService, $location, $rootScope,locals) {
            $('.login-view-box .error').show();
            $rootScope.$on('$stateChangeSuccess', function () {
                var currentUrl = $location.url();
                $scope.showGoLogin = currentUrl == '/login';
            });

            var showError=function (desc) {
                $scope.error=desc;
                $scope.isErrorShow=true;
            }

            $(".login-form [require]").on('input', function() {
                $scope.isErrorShow=false;
            })

            $scope.check=function(type,success){
                if(type==1){
                    if($scope.account==null||$scope.account==''){
                        showError("手机号码不能为空")
                        return false;
                    }else if(!(/^1[3|4|5|8][0-9]\d{8}$/.test($scope.account))){
                        showError('您输入的手机号码不正确,请重新输入');
                        return false;
                    }
                }
                if(type==2){
                    if($scope.account==null||$scope.account==''){
                        showError("手机号码不能为空")
                        return false;
                    }else if(!(/^1[3|4|5|8][0-9]\d{8}$/.test($scope.account))){
                        showError('您输入的手机号码不正确,请重新输入');
                        return false;
                    }else if($scope.password==null||$scope.password==''){
                        showError("密码不能为空")
                        return false;
                    }else if(success!=null){
                        success();
                    }
                }
            }
            $scope.isCustsSelectShow=false;
            var resultTemp ={}
            $scope.login=function () {

                $scope.check(2,function () {
                    adService.postWithLoading("user/login",{account:$scope.account,password:$scope.password},
                        function (res) {
                            resultTemp = res.result;
                            if(!res.result||!res.result.custs){
                                showTip("获取用户数据失败!");
                            }else if(res.result.custs.length>1){
                                $('#account').attr("disabled",true);
                                $('#password').attr("disabled",true);
                                $('#loginBtn').attr("disabled",true);
                                $scope.isCustsSelectShow=true
                                $scope.custs=res.result.custs;
                            }else{  
                                locals.setObject("token",res.result);   //设置数据
                                window.location.href = "index.html";
                            }
                        },function (res) {
                            console.info('Login Error!')
                            if(res.code==-3){
                                showError(res.desc)
                            }else{
                                showError("您输入的手机号或密码不正确,请重新输入。")
                            }
                        });
                });

            }

            //选择商客
            $scope.custsChange = function (custsSelect) {
                console.info(custsSelect);
                for(i in resultTemp.custs){
                     if(resultTemp.custs[i].name == custsSelect){
                        var temp = resultTemp.custs[i];
                         resultTemp.custs.splice(0,resultTemp.custs.length);
                         resultTemp.custs.push(temp);
                     }
                }
                console.info(resultTemp);
                locals.setObject("token",resultTemp);
                window.location.href = "index.html";
            }
        }
    ])
网友评论