JavaScript常用方法总结

在web开发中,由于需要会涉及到一些js,自己记性不是很好,将自己在开发中经常用到的一些JS或是轮子总结一下。

JS获取项目路径

1.获取项目的绝对路径

var local = window.location;  
var contextPath = local.pathname.split("/")[1];  
var basePath = local.protocol+"//"+local.host+"/"+contextPath; 

执行结果:

http://localhost:8080/test

2.获取项目的相对路径

var pathName = document.location.pathname;
var index = pathName.substr(1).indexOf("/");
var basePath= pathName.substr(0,index+1);

执行结果:

pathName===/test/index.jsp
basePath===/test

第二种方式加载更快

基于Jquery的Ajax交互

1.常规方式调用ajax

 $.ajax({
        type: "POST",
        dataType:"JSON",
        async:false,
        url: basePath+'/book/mApply.do?',
        data:{
          "bookId":bookId
        },
        success: function(result){
        	if(result.success){
        		$("#applyBorrow1").innerHTML="已申请";	
        		$("#bookHadNow").innerHTML="库存:"+(bookHadNow-1)+"<br>";
        		$("#applyBorrow1").disabled=true;				        		
        	}else{
        		var btn1 = ['确定'];
        		mui.alert('该书无库存,申请失败', '', btn1, function(e) {
        		window.location.reload();
        		});
        	}
         }
    })

2.文件上传ajax(注意与第一种方法参数的区别)

$.ajax({
	async : false,
	cache : false,
	type : "post",
	data : formData,
	url : '/ggqyy/menu/uploadExcelFile.do',
	dataType : 'json',
	contentType: false, //必须
	processData: false, //必须
	success : function(result) {
		if(result.success){
			$.messager.alert('操作成功',result.data);	
		}else{
			$.messager.alert('操作失败',result.data);
		}
	},
	error : function(arg1, arg2, arg3) {
		console.log(arg1 + "--" + arg2 + "--" + arg3);
	}
});		

JS循环执行

setTimeout() 方法用于在指定的毫秒数后调用函数或计算表达式。 

扫描二维码关注公众号,回复: 3370313 查看本文章

setTimeout(code,millisec),code:要调用的函数后要执行的 JavaScript 代码串。  millisec:在执行代码前需等待的毫秒数。 

 $(document).ready(function(){
    	setTimeoutDemo(); 
    })

  function setTimeoutDemo() {
       findOrderList();                     //定时调用函数
       setTimeout(setTimeoutDemo,5000);     //设置定时时间
   }

获取语音播报

调用百度提供的外部API,text参数即为播报文本内容

//语音播报 
    function speckText(text){
        var url = "http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&text=" + encodeURI(text);        
        var n = new Audio(url);
        n.src = url;
        n.play();
    }

JS日期操作

1. 实现Date数据类型 -> (年份-月份-日期 HH:mm:ss) 格式转换

function jsonDateFormat6(date) {//json日期格式转换为正常格式(年份-月份-日期 HH:mm:ss)
	    try { 
	    	if(date=='') return "";
	    	var time = date.time;
	        var date = new Date(date.time);
	        var year = date.getFullYear();
	        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
	        var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
	        var hours = date.getHours() < 10 ? "0" + date.getHours():date.getHours();
	        var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes():date.getMinutes();
	        var seconds = date.getSeconds(); 
	        var now = new Date();
	        var daff = now.getTime()-time;     
	        var nowYear = now.getFullYear();
	        var nowMonth = now.getMonth() + 1 < 10 ? "0" + (now.getMonth() + 1) : now.getMonth() + 1;
	        var nowDay = now.getDate() < 10 ? "0" + now.getDate() : now.getDate();
	        return  year + "-" + month + "-" + day + " " + hours + ":" +  minutes + ":" + seconds;
	    } catch (ex) { 
	        return "";
	    }
	}

2. 实现Date数据类型 -> (年份-月份-日期) 格式转换

function jsonDateFormat5(date) {//json日期格式转换为正常格式(年份-月份-日期)
	    try { 
	    	if(date=='') return "";
	    	var time = date.time;
	        var date = new Date(date.time);
	        var year = date.getFullYear();
	        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
	        var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();       	        
	        var now = new Date();
	        var daff = now.getTime()-time;        
	        var nowYear = now.getFullYear();
	        var nowMonth = now.getMonth() + 1 < 10 ? "0" + (now.getMonth() + 1) : now.getMonth() + 1;
	        var nowDay = now.getDate() < 10 ? "0" + now.getDate() : now.getDate();
	        return  year + "-" + month + "-" + day  ;
	    } catch (ex) { 
	        return "";
	    }
	}

3. 实现Date数据类型 -> (yyyyMMdd) 格式转换

//日期格式化
function getyyyyMMdd(d){
    var curr_date = d.getDate();
    var curr_month = d.getMonth() + 1; 
    var curr_year = d.getFullYear();
    String(curr_month).length < 2 ? (curr_month = "0" + curr_month): curr_month;
    String(curr_date).length < 2 ? (curr_date = "0" + curr_date): curr_date;
    var yyyyMMdd = curr_year + "" + curr_month +""+ curr_date;
    return yyyyMMdd;
}  

4. 获取当前日期

function getToday(){
    var today = new Date();
    var year = today.getFullYear();
    var month = today.getMonth()+1;
    var day = today.getDate();
    if (month<10){
        month = "0"+month;
    }if (day<10){
        day = "0"+day;
    }
    todayResult = new Date(year+"-"+month+"-"+day); 
})

5. 获取前一天日期

function preDay(todayResult){
	 todayResult.setDate(todayResult.getDate()-1);
}

6. 获取下一天日期

 function nextDay(todayResult){
	 todayResult.setDate(todayResult.getDate()+1);
 }

7. 判断当前日期为一年中的第几周

//(根据日期)获取当前年份,当前周数
    function getWeekOfYear(today){
        if (today == null){
            today = new Date();
        }else{
            today = new Date(today);
        }
        var firstDay = new Date(today.getFullYear(),0, 1);
        var dayOfWeek = firstDay.getDay();
        var spendDay= 1;
        if (dayOfWeek !=0) {
            spendDay=7-dayOfWeek+1;
        }
        firstDay = new Date(today.getFullYear(),0, 1+spendDay);
        var d =Math.ceil((today.valueOf()- firstDay.valueOf())/ 86400000);
        var result =Math.ceil(d/7);
        //周数初始化
        var _yearResult = today.getFullYear();
        var _weekNumResult = result+1;
        //年份,周数集合
        var yearWeekNum = {
            year:today.getFullYear(),
            weekNum:result+1
        }
        //var resultMsg = "当前是"+yearResult+"年"+weekNumResult+"月";
        $("#weekInfo").html(_yearResult+"年第 "+_weekNumResult+" 周");
        return _yearResult+"#"+_weekNumResult;
    };

猜你喜欢

转载自blog.csdn.net/zhang_jiayuan/article/details/81205953