`
xurichusheng
  • 浏览: 336073 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

XMLHttpRequest 实例

    博客分类:
  • ajax
阅读更多

 

// JavaScript source code

//获取httprequest对象
var http=getHttpObject();

function getHttpObject()
{
	var xmlhttp=false;
	//Mozilla、Safari等非IE浏览器
	if(window.XMLHttpRequest)
	{
		xmlhttp=new XMLHttpRequest();
	/*如果来自服务器的响应没有XML mime-type头,
	一些Mozilla浏览器的某些版本可能无法正常工作。
	为了解决这个问题,如果服务器发送的头不是text/xml,可调用另外方法来忽略该头。
	*/
		if(xmlhttp.overrideMimeType)
		{
			xmlhttp.overrideMimeType('text/xml');
		}
	}
	//IE浏览器
	else
	{
	//新版本的IE
		try{
			xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
		}catch(e)
		{
			try
			{
		//旧版本的IE
				xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
			}catch(E)
			{
				xmlhttp=false;
			}
		}
	}
	return xmlhttp;
}
//发送request对象
function sendHttpRequest()
{
	//判断下如果http对象不存在则退出
	if(!http)
	{
		alert("The XMLHttpRequest Can't be created!");
		return false;
	}
	var url="/do/login";
	//以上为两种方式的公用代码部分,请注意区分以下两种发送方式的查询字符串以及对应的发送方式;
	//使用GET方式发送
	url+="?username=davidchow&userpassword=james";
	http.open('GET',url,true);
	http.onreadystatechange=processHttpRequest;
	http.send(null);
	/*使用POST方式发送
	http.open('POST',url,true);
	http.onreadystatechange=processHttpRequest;
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
	http.send("username=davidchow&userpassword=james");
	*/
}
//处理服务器返回response对象
function processHttpRequest()
{
	if (http.readyState == 4) { 
		// 一切正常,响应已收到 
            if (http.status == 200) {
            	//十分好!已经收到返回的信息!可能为两种类型的返回
            	//返回无格式状态的文本字符串(msg是指HTML中的成对元素的ID名)
            	document.getElementById("msg").innerText=http.responseText;
				/*下面这种返回的是有格式状态的文本字符串!
				document.getElementById("msg").innerHTML=http.responseText;
            	下面这种返回xml文档,大家可以使用在XML课程中学到的知识来扩展这类方法的使用!
            	http.responseXML;
            	*/
            	
            } else {
            	alert("this page is err");
            }
        }
        else
        {
			//尚未就绪!或者正在等待服务器响应!
			alert("Please Wait!Loading....!")
        }
}

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics