创建XMLHttpRequest对象的js文件(适用asp,php,jsp,asp.net等)
Ajax.js
function
Ajax()
{
var xmlHttp = null ;
if (window.XMLHttpRequest)
{ // 非IE内核浏览器
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{ // IE内核浏览器
try
{ // IE6.0
xmlHttp = new ActiveXObject( " Microsoft.XMLHTTP " );
}
catch (e1)
{
try
{
xmlHttp = new ActiveXObject( " MSXML2.XMLHTTP " );
}
catch (e2)
{
try
{
xmlHttp = new ActiveXObject( " MSXML3.XMLHTTP " );
}
catch (e3)
{
alert( " 创建Ajax失败: " + e3)
}
}
}
}
else
{ // 未知浏览器
alert( " 未能识别的浏览器 " );
}
return xmlHttp;
}
{
var xmlHttp = null ;
if (window.XMLHttpRequest)
{ // 非IE内核浏览器
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{ // IE内核浏览器
try
{ // IE6.0
xmlHttp = new ActiveXObject( " Microsoft.XMLHTTP " );
}
catch (e1)
{
try
{
xmlHttp = new ActiveXObject( " MSXML2.XMLHTTP " );
}
catch (e2)
{
try
{
xmlHttp = new ActiveXObject( " MSXML3.XMLHTTP " );
}
catch (e3)
{
alert( " 创建Ajax失败: " + e3)
}
}
}
}
else
{ // 未知浏览器
alert( " 未能识别的浏览器 " );
}
return xmlHttp;
}
放到创建对象的页面
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
用asp举个例子
<
script language
=
"
javascript
"
type
=
"
text/javascript
"
src
=
"
Ajax.js
"
></
script
>
< script language = " javascript " type = " text/javascript " >
var xmlHttp = new Ajax();
function checkName()
{
xmlHttp.onreadystatechange = getName;
xmlHttp.open( " get " , " getName.asp " , true );
xmlHttp.send( null )
}
function getName()
{
var dom = document.getElementById( " name " )
if (xmlHttp.readystate == 1 )
{
dom.value = " 正在连接服务器 "
}
else if (xmlHttp.readystate == 2 || xmlHttp.readystate == 3 )
{
dom.value = " 正在读取数据 " ;
}
else if (xmlHttp.readystate == 4 )
{
if (xmlHttp.status == 200 )
{
dom.value = xmlHttp.responseText
}
}
}
</ script >
< script language = " javascript " type = " text/javascript " >
var xmlHttp = new Ajax();
function checkName()
{
xmlHttp.onreadystatechange = getName;
xmlHttp.open( " get " , " getName.asp " , true );
xmlHttp.send( null )
}
function getName()
{
var dom = document.getElementById( " name " )
if (xmlHttp.readystate == 1 )
{
dom.value = " 正在连接服务器 "
}
else if (xmlHttp.readystate == 2 || xmlHttp.readystate == 3 )
{
dom.value = " 正在读取数据 " ;
}
else if (xmlHttp.readystate == 4 )
{
if (xmlHttp.status == 200 )
{
dom.value = xmlHttp.responseText
}
}
}
</ script >