myhttp.js //异步请求封装var http = { xmlHttp : null, createNew: function(){ var http = {}; //Mozilla 浏览器(将XMLHttpRequest对象作为本地浏览器对象来创建) if(window.XMLHttpRequest){ //Mozilla 浏览器 http.xmlHtt
//异步请求封装
var http = {
xmlHttp : null,
createNew: function(){
var http = {};
//Mozilla 浏览器(将XMLHttpRequest对象作为本地浏览器对象来创建)
if(window.XMLHttpRequest){ //Mozilla 浏览器
http.xmlHttp = new XMLHttpRequest();
}else if(window.ActiveXObject) { //IE浏览器
//IE浏览器(将XMLHttpRequest对象作为ActiveX对象来创建)
try{
http.xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try {
http.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
if(http.xmlHttp === null){
console.log("不能创建XMLHttpRequest对象");
return false;
}
//发出异步请求的方法
http.sendAsynchronRequest=function(url,parameter,callback){
if(parameter === null){
//设置一个事件处理器,当XMLHttp状态发生变化,就会出发该事件处理器,由他调用
//callback指定的javascript函数
http.xmlHttp.onreadystatechange = callback;
//设置对拂去其调用的参数(提交的方式,请求的的url,请求的类型(异步请求))
http.xmlHttp.open("GET",url,true);//true表示发出一个异步的请求。
http.xmlHttp.send(null);
}else{
http.xmlHttp.onreadystatechange = callback;
http.xmlHttp.open("POST",url,true);
http.xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
http.xmlHttp.send(parameter);
}
};
//获取返回数据
http.GetRequestData=function(){
try
{
if (myhttp.xmlHttp.readyState == 4) {
if (myhttp.xmlHttp.status == 200) {
if(myhttp.xmlHttp.responseText !== null && myhttp.xmlHttp.responseText !== ""){
//console.log(myhttp.xmlHttp.responseText);
return myhttp.xmlHttp.responseText;
}
}
}
if (myhttp.xmlHttp.readyState == 1)
{
console.log("正在加载连接对象......");
}
if (myhttp.xmlHttp.readyState == 2)
{
console.log("连接对象加载完毕。");
}
if (myhttp.xmlHttp.readyState == 3)
{
console.log("数据获取中......");
}
}
catch (e)
{
console.log(e);
}
};
return http;
}
};
//调用方法
var myhttp = http.createNew();
var url='http://xxx.comtest';
myhttp.sendAsynchronRequest(url,'test=0001',function(){
var result=myhttp.GetRequestData();
if(result){
console.log(result);
}
});
