ajax ,get,post方式同时实现

//method               //代表可以是 post 和 get 方式
//url                //代表 地址
//data              //代表向服务器发送的请求参数
//success         //代表操作函数

function ajax(method, url, data, success) {
	var xhr = null;
	try {
		xhr = new XMLHttpRequest();
	} catch (e) {
		xhr = new ActiveXObject('Microsoft.XMLHTTP');
	}
	
	if (method == 'get' && data) {
		url += '?' + data;
	}
	
	xhr.open(method,url,true);       
	if (method == 'get') {
		xhr.send();
	} else {
		xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
		xhr.send(data);       //这里面写传送的参数
	}
	
	xhr.onreadystatechange = function() {
		
		if ( xhr.readyState == 4 ) {
			if ( xhr.status == 200 ) {
				success && success(xhr.responseText);      //调用函数实现具体功能
			} else {
				alert('出错了,Err:' + xhr.status);
			}
		}
		
	}
}

猜你喜欢

转载自blog.csdn.net/qq_38340601/article/details/80085990