关闭

js ajax

标签: xmlhttprequestnullfunctioncallbackajaxurl
480人阅读 评论(0) 收藏 举报
/**
*@author shining 251310858@qq.com
var res = sendRequest({
	url : "1.php", //necessary
	method : "post",
	params : {
		param1 : "123",
		param2 : "234"
	},
	async : false,
	callback : function(res){
	}
});
*/
var javascriptHttpRequest;
var javascriptHttpResponseText;
function createXMLHttpRequest(){
	if(window.XMLHttpRequest){ //Mozilla
		javascriptHttpRequest = new XMLHttpRequest();
	}else if(window.ActiveXObject){ //IE
		try{
			javascriptHttpRequest = new ActiveXObject("Msxm12.XMLHTTP");
		}catch(e){
		try{
			javascriptHttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
		}catch(e){}
		}
	}
}

function sendRequest(o){
	if(o.url == null){
		return;
	}
	function processResponse(){
		if(javascriptHttpRequest.readyState == 4){
			if(javascriptHttpRequest.status == 200){
				if(o.callback != null){
					o.callback(javascriptHttpRequest);
				}
				javascriptHttpResponseText = javascriptHttpRequest.responseText;
			}
		}
	}
	createXMLHttpRequest();
	var param = "";
	if(o.method == null){
		o.method = "get";
	}
	if(o.async == null){
		o.async = true;
	}
	if(o.params == null){
		param = null;
	}else{
		for (key in o.params)
		{
			param = param + key + "=" + o.params[key]+"&";
		}
		param = param.substring(0,param.length-1);
		if(o.method == "get"){
			o.url = o.url + "?" + param;
		}
		
	}
	javascriptHttpRequest.open(o.method,o.url,o.async);
	javascriptHttpRequest.onreadystatechange = processResponse;
	javascriptHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded;"); 
	javascriptHttpRequest.send(param);
	return javascriptHttpResponseText;
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:36236次
    • 积分:427
    • 等级:
    • 排名:千里之外
    • 原创:8篇
    • 转载:5篇
    • 译文:0篇
    • 评论:5条
    文章分类