用 2 个函数实现 Ajax

Ajax 技术现在好多人懂了,但用的时候,代码五花八门,不易理解和维护。现在已经有一些 Ajax 框架,做的很不错,例如较早的 xAjax(PHP下的),还有现在的 jQuery、Dhtml 等。但因为框架要考虑通用性和兼容性等,实现起来叠床架屋的,比较复杂。对于我们一些小应用来说,用起来有大材小用、打炮大蚊子的感觉。

其实 Ajax 被大家搞的神秘了 - 看看书店里那些千篇一律的、煞有介事的专门讲 Ajax 的书吧。

以下代码把通过 get 方式实现 Ajax 请求的方法,构造成 2 个函数(不打算用类来实现),已经可以满足日常的简单应用,也几乎体现了 Ajax 的全部精髓。用的时候,给几个参数,调用函数就可以了。

function getAjax(httpurl,requests,div)
{
 if (typeof(httpurl,requests,div) == 'undefined')
 {
  return false;
 }
var url = httpurl+requests;
var show = document.getElementById(div);
 var ajax = InitAjax();
 ajax.open("GET", url, true);
 ajax.onreadystatechange = function() {
  if (ajax.readyState == 4 && ajax.status == 200) {
   show.innerHTML = ajax.responseText;
  }
 }
 ajax.send(null);
}

function InitAjax()
{
 var ajax=false;
 try {
  ajax = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   ajax = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   ajax = false;
  }
 }
 if (!ajax && typeof XMLHttpRequest!='undefined') {
  ajax = new XMLHttpRequest();
 }
 return ajax;
}

张庆(网眼) 2008-11-25
来自“网眼视界”:http://blog.why100000.com
“十万个为什么”电脑学习网:http://www.why100000.com

你可能感兴趣的:(jquery,Ajax,框架,PHP,Microsoft)