// Written by G Zhao, 仅做交流
var METHOD_GET = 'GET';
var METHOD_POST = 'POST';
//创建XmlHttp对象,并定义回调函数
function InitializeXmlHttpObject()
{
var http_request = null;
if ( window.ActiveXObject )// IE
{
try
{
http_request = new ActiveXObject( "Msxml2.XMLHTTP" );
}
catch (e)
{
try
{
http_request = new ActiveXObject( "Microsoft.XMLHTTP" );
}
catch (e) {}
}
}
if ( window.XMLHttpRequest )
{
http_request = new XMLHttpRequest();
http_request.overrideMimeType( 'text/xml' );
}
if (!http_request) // 异常,创建对象实例失败
{
return false;
}
http_request.onreadystatechange = processRequest;
return http_request;
}
//使用方法:
//调用下面的方法开始异步调用
//AjaxIt( METHOD_GET/METHOD_POST, 'Http://xxx/xx.aspx', postdata/null );
//其中 METHOD_GET/METHOD_POST 分别为 GET 和 POST 方法,
//GET 方法为通过URL跟参数的方式向服务端页面传送数据,第三个参数为null,
//POST 方法为通过post数据的方法向服务端页面传送数据,第三个参数为要POST的数据。
//在页面中添加 go(responseText){}方法,
//一旦服务端处理页面完成操作便执行go方法,responseText为服务端页面返回的值
function AjaxIt( method, postbackurl, postdata )
{
xmlHttpObject = InitializeXmlHttpObject();
if( method.toUpperCase() == METHOD_GET )
{
xmlHttpObject.open( METHOD_GET, postbackurl, true );
xmlHttpObject.send( null );
}
if( method.toUpperCase() == METHOD_POST )
{
xmlHttpObject.open( METHOD_POST, postbackurl, true );
xmlHttpObject.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpObject.send( postdata );
}
}
//回调函数
function processRequest()
{
if (http_request.readyState == 4) // 判断对象状态
{
if (http_request.status == 200) // 信息已经成功返回,开始处理信息
{
go(http_request.responseText); //调用go方法
}
else //页面不正常
{
alert("The Page Requested maybe have some Trouble.");
}
}
}
本文介绍了一种使用JavaScript实现Ajax异步请求的方法,包括GET和POST两种方式,并提供了回调函数处理响应结果。

454

被折叠的 条评论
为什么被折叠?



