以前一直使用Asp.net自带的Ajax方法,所以对Ajax没有深入的研究,最近开始编写PHP代码,PHP没有自带的AJax方法,所以就在网上研究了一把。
网上方法很多,总结了各方面的资料之后我做了一个简单的封装,方便大家调用。
第一步:将下面代码保存到JS文件。如:Ajax.js
/********************************************************/
/* AJax.js */
/* */
/* 使用 xmlHttpObject 对象与服务器进行无刷新提交等 */
/* */
/* Powered by Sean */
/* Email:sean.lxy@qq.com QQ:13261953 */
/********************************************************/
var LS_AJax = (function () {
var result = {
PostData : function (url, fun, postdata) {
var xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("浏览器不支持 HTTP Request");
return;
}
postdata += "&t=" + Math.random();
xmlHttp.open("Post", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200 && fun && (typeof fun == "function"))
fun(xmlHttp.responseText);
};
xmlhttp.send(postdata);
xmlhttp = null;
},
GetURL : function (url, fun) {
var xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("浏览器不支持 HTTP Request");
return;
}
url += "&t=" + Math.random();
xmlHttp.open("Get", url, true);
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200 && fun && (typeof fun == "function"))
fun(xmlHttp.responseText);
}
xmlhttp.send();
xmlhttp = null;
}
};
var GetXmlHttpObject = function () {
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
return xmlhttp;
};
return result;
})();
第二步:在需要使用ajax的页面里调用该js:
<script language="javascript" type="text/javascript" src="JS/AJax.js"></script>
然后加入以下代码:
<pre class="javascript" name="code"><script language="javascript" type="text/javascript">
//需要调用ajax的地方
function BeginLoad() {
//通过Get方式获取服务器数据 LS_AJax.GetURL(服务器端脚本地址, 服务器返回后回调方法);
LS_AJax.GetURL("index.php?t=" + Math.random(), endLoad);
//通过Post方式提交数据 LS_AJax.PostData(服务器端脚本地址, 服务器返回后回调方法, 提交的数据);
LS_AJax.PostData("index.php?t=" + Math.random(), endLoad, "a=15&b=65");
}
//服务器返回后的调用的方法 str 为服务器返回数据。
function endLoad(str) {
//弹出服务器返回内容
alert(str);
}
</script>
至于服务器端代码如何编写,大家可以根据实际情况编写即可,服务器段不限类型,asp.net、 php、 jps 等都行。
如PHP
<?php
echo date('Y-m-d H:i:s',time());
?>
调用后将提示服务器当前时间。