文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>ajax 简单封装

ajax 简单封装

时间:2010-07-16  来源:vinchen

<!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

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载