• 【前端学习笔记04】JavaScript数据通信Ajax方法封装


    //Ajax 方法封装 
    //设置数据格式
    function setData(data){
    	if(!data){
    		return '';
    	}
    	else{
    		var arr = [];
    		for(k in data){
    			if(!data.hasOwnProperty(k)) continue;
    			if(typeof data[k] == 'function') continue;
    			var value = data[k].toString();
    			var key = encodeURIComponent(k);
    			value = encodeURIComponent(value);
    			arr.push(key + '=' + value);
    		}
    		return arr.join('&');
    	}
    }
    //get()方法封装
    function get(url,obj,callback){
    	var xhr = null;
    	if(window.XMLHttpRequest){
    		xhr = new XMLHttpRequest();
    	}
    	else{
    		xhr = new ActiveXObject('Microsoft.XMLHTTP');
    	}
    	url = url + '?'+ setData(obj);
    	xhr.open('get',url,true);
    	xhr.onreadystatechange = function(){
    		if(xhr.readyState == 4){
    			if(xhr.status == 200){
    				callback(xhr.responseText);
    			}
    		}
    	}
    	xhr.send(null);
    }
    
    //post()方法封装
    function post(url,obj,callback){
    	var xhr = null;
    	var postBody = setData(obj);
    	if(window.XMLHttpRequest){
    		xhr = new XMLHttpRequest();
    	}
    	else{
    		xhr = new ActiveXObject('Microsoft.XMLHTTP');
    	}
    	xhr.open('post',url,true);
    	xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    	xhr.onreadystatechange = function(){
    		if(xhr.readyState == 4){
    			if(xhr.status == 200){
    				callback(xhr.responseText);
    			}
    		}
    	}
    	xhr.send(postBody);
    }
  • 相关阅读:
    xxx
    cdq分治入门--BZOJ1176: [Balkan2007]Mokia
    cdq分治入门--BZOJ3262: 陌上花开
    本月题量 171122晚-171222午
    cdq分治入门--BZOJ1492: [NOI2007]货币兑换Cash
    NOIP2017游记
    xx
    CF601D:Acyclic Organic Compounds
    LOJ#539. 「LibreOJ NOIP Round #1」旅游路线
    composer常用的一些命令参数说明
  • 原文地址:https://www.cnblogs.com/zachary93/p/6054481.html
Copyright © 2020-2023  润新知