posts - 4, comments - 3, trackbacks - 0, articles - 0

Ajax开发记录一: xmlhttp创建的一种方式

Posted on 2007-02-28 15:40 青岛小哥 阅读(171) 评论(0)  编辑  收藏 所属分类: JSPAJAX

编写一个js文件。如functions.js。用来存放要使用到的js函数。文件开头如下:
            (判断浏览器类型和版本,并创建相应的xmlhttp实例)

 1      // functions.js
 2     
 3      // Create a boolean variable to check for a valid MS instance.
 4      var  xmlhttp  =   false ;
 5     
 6      // Check if we are using IE.
 7      try   {
 8          // If the javascript version is greater than 5.
 9         xmlhttp  =   new  ActiveXObject( " Msxml2.XMLHTTP " );
10     }
  catch  (e)  {
11          // If not, then use the older active x object.
12          try   {
13              // If we are using IE.
14             xmlhttp  =   new  ActiveXObject( " Microsoft.XMLHTTP " );
15         }
  catch  (E)  {
16              // Else we must be using a non-IE browser.
17             xmlhttp  =   false ;
18         }

19     }

20     
21      // If we are using a non-IE browser, create a javascript instance of the object.
22      if  ( ! xmlhttp  &&   typeof  XMLHttpRequest  !=  'undefined')  {
23         xmlhttp  =   new  XMLHttpRequest();
24     }

然后在后面的函数中可以调用xmlhttp:(如下例)
 1 // A variable used to distinguish whether to open or close the calendar.
 2      var  showOrHide  =   true ;
 3     
 4      function  showHideCalendar()  {
 5         
 6          // The location we are loading the page into.
 7          var  objID  =   " calendar " ;
 8         
 9          // Change the current image of the minus or plus.
10          if  (showOrHide  ==   true ) {
11              // Show the calendar.
12             document.getElementById( " opencloseimg " ).src  =   " images/mins.gif " ;
13              // The page we are loading.
14              var  serverPage  =   " calendar.php " ;
15              // Set the open close tracker variable.
16             showOrHide  =   false ;
17             
18              var  obj  =  document.getElementById(objID);
19             xmlhttp.open( " GET " , serverPage);
20             xmlhttp.onreadystatechange  =   function ()  {
21                  if  (xmlhttp.readyState  ==   4   &&  xmlhttp.status  ==   200 {
22                     obj.innerHTML  =  xmlhttp.responseText;
23                 }

24             }

25             xmlhttp.send( null );
26         }
  else   {
27              // Hide the calendar.
28             document.getElementById( " opencloseimg " ).src  =   " images/plus.gif " ;
29              // The page we are loading.
30              var  serverPage  =   " blank.php " ;
31             showOrHide  =   true ;
32             
33             document.getElementById(objID).innerHTML  =   "" ;
34         }

35         
36         
37     }

只有注册用户登录后才能发表评论。


网站导航: