封装原生ajax

function Ajax(args){
	this.url = args.url;
	this.type = args.type;
	this.data = args.data;
}

Ajax.prototype.post=function(){

	var xhr = window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject(Microsoft.XMLHTTP);
	xhr.open(this.type, this.url, true);
	if (this.type == 'post') {
	    //给指定的HTTP请求头赋值
	    xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded;charset=UTF-8');
	}
	xhr.send(jsontokv(this.data));
	xhr.onreadystatechange = function() {
	    // readyState == 4说明请求已完成
	    if (xhr.readyState == 4 && xhr.status == 200) {
	        console.log(xhr.responseText);
	    }
	}
}


function jsontokv(jsonData){
	var ky='';
	for(var k in jsonData){
		ky+=(k+"="+jsonData[k]+"&");
	}
	return ky.substring(0,ky.length-1);
}



	
	index page
	
	


	
	

 

你可能感兴趣的:(原生js,ajax,JavaScript,前端,前后分离,js,海边拾贝)