`
ccw5510
  • 浏览: 7851 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

ajax 简单封装

阅读更多
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>ajax</title>
<script type="text/javascript"><!--
function Ajax() {
var xmlHttpReq = null;
if (window.XMLHttpRequest) {
  xmlHttpReq = new XMLHttpRequest();
} else {
  if (window.ActiveXObject) {
    var versions = ['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Microsoft.XMLHTTP',
 'Msxml2.XMLHTTP.7.0', 'Msxml2.XMLHTTP.6.0',
 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 
 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];
    for(var i=0; i<versions.length; i++) {
      try {
        xmlHttpReq = new ActiveXObject(versions[i]);
        if(xmlHttpReq) {
          break;
        }
      } catch(e) {}
    }
  }
}
	
var handler = null;
	
this.invoke = function (mode, url, value, _handler) {
  handler = _handler;
  if(mode == 'get') {
    var querystring = url+'?'+value+'&'+Math.random();
    if(window.XMLHttpRequest) {
      xmlHttpReq.open('GET', querystring);
      xmlHttpReq.onreadystatechange = this.callback;
      xmlHttpReq.send(null);
    } else {
      xmlHttpReq.open('GET', querystring, true);
      xmlHttpReq.onreadystatechange = this.callback;
      xmlHttpReq.send();
    }
  }
  else if(mode == 'post') {
    xmlHttpReq.open('POST', url);
    xmlHttpReq.onreadystatechange = this.callback;
    xmlHttpReq.setRequestHeader('Content-Type',
 'application/x-www-form-urlencoded');
    xmlHttpReq.send(value);
  }
};
	
this.callback = function () {
  if (xmlHttpReq.readyState == 4) {
    if (xmlHttpReq.status == 200) {
      handler(xmlHttpReq.responseText);
    } else {
      alert("请刷新页面!");
    }
  }
};
}

// 调用示例
new Ajax().invoke(
  "get",
  "/index.php",
  'name=hello',
  run
);

function run(response) {
  alert(response);
}
// --></script>
</head>

<body>
</body>
</html>

 index.php

<?php
echo $_GET['name'];

// echo $_POST['name'];
?>

 

  兼容 IE、firefox、chrome 等浏览器。

  var querystring = url+'?'+value+'&'+Math.random();,Math.random() 主要是进行 GET 请求时为了防止缓存。

  发送请求时,对数据最好进行 urlencode 编码。

  示例代码:点击下载

 

By xhttp.cn 整理:http://www.xhttp.cn/2010/06/18

0
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics