zoukankan      html  css  js  c++  java
  • 【前端学习笔记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);
    }
  • 相关阅读:
    etherlime-1-Quick Start
    etherlime-4-Etherlime CLI
    Sequelize-nodejs-2-basic usage
    Sequelize-nodejs-6-Instances
    Sequelize-nodejs-5-Querying
    Sequelize-nodejs-4-Model usage
    Sequelize-nodejs-3-model definition
    eclipse快捷键大全
    java第一课
    java程序员认证考试题库
  • 原文地址:https://www.cnblogs.com/zachary93/p/6054481.html
Copyright © 2011-2022 走看看