【www.gdgbn.com--浏览器】

js xmlhttp对象ie浏览器和非ie浏览器创建方法


    例子:创建一个xmlhttp对象,并向服务器请求一个xml文档,返回文档后显示。下面分别就ie和非ie进行实例讲解

    1) ie浏览器使用activexobject方式创建xmlhttp对象:

   

   var xmlhttpreq = new activexobject("msxml2.xmlhttp.3.0");

      xmlhttpreq.open("get", "http://localhost/test.xml", false);

      xmlhttpreq.send();

      alert(xmlhttpreq.responsetext);

    2) 非ie浏览器使用xmlhttprequest方式创建xmlhttp对象:

     

 var xmlhttpreq = new xmlhttprequest();

      xmlhttpreq.open("get", "http://localhost/test.xml", false);

      xmlhttpreq.send();

      alert(xmlhttpreq.responsetext);

  2.2 创建完xmlhttp对象以后,因为它是一套api,所以它有很多的方法和属性,如上面用到的open()、send()、responsetext。

    xmlhttp对象的代码处理方式比较固定。因此下面要做的就只是按例子顺序进行理解就可以了。

下面看一款完整的实例

js 兼容ff activexobject创建xmlhttp方法
*/

function createxmlhttpobject()
 {
  var xobject = null;
  try
  {
   xobject = new activexobject("msxml2.xmlhttp.4.0");
  }
  catch (e)
  {
   try
   {
    xobject = new xmlhttprequest();
    if(xobject.overridemimetype){
     xobject.overridemimetype("text/xml");
    }
   }
   catch (e)
   {
    try
    {
     xobject = new activexobject("msxml2.xmlhttp");
    }
    catch (e)
    {
     try
     {
      xobject = new activexobject("microsoft.xmlhttp");
     }
     catch (e)
     { 
      alert("error: unable to create xml http object!");
     }
    }
   }
  }
  return xobject;
 }
 
 function initrequest(){
  request = createxmlhttpobject();
 }

本文来源:http://www.gdgbn.com/bangongshuma/28851/