/*
使用方法:
ajax_get("url.PHP",回调函数);
回调函数中有一个参数是文本型的,是服务器返回来的,如果回调函数名是call_back,那么我们可以这样定义它:
function call_back(text_from_server)
{
alert(text_from_server);
}
注意目前回调函数只有一个参数,参数名可以自定.
ajax_post("url.PHP","参数",回调函数);和ajax_get大同小异,不再介绍
*/
//--------------------------------------------------------------------框架开始
function getXmlHttpObject()
{
/* Create a new XMLHttpRequest object to talk to the Web server */
var xmlHttp = false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
@end @*/
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}
function ajax_get(url,callback)
{
xmlHttp.open("GET",url,true);
xmlHttp.onreadystatechange =function(){ handleReadyState(callback); }
xmlHttp.send(null);
}
/**
*@ url处理页面的地址,比如:
*@ param 参数比如 name=yangQingRong&birth=1985&city=jieyang
*@ callback 回调函数的句柄 比如有一个函数function sayHello(name1){},那么我们填"sayHello"
*/
function ajax_post(url,param,callback)
{
xmlHttp.open("POST",true);
xmlHttp.onreadystatechange=function(){ handleReadyState(callback); }
xmlHttp.setRequestHeader("Content-Length",param.length);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.send(param);
}
function handleReadyState(callback) {
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
callback(response);
}
}
var xmlHttp=getXmlHttpObject();
//--------------------------------------------------------------------框架结束
ajax.htm
<script language="javascript" src="ajax1.js"></script>
<script language="javascript">
ajax_get("ajax.PHP",back);
var name="杨庆荣!";
//name= escape(name);
ajax_post("ajax.PHP","name="+name,back2);
function back2(res)
{ alert(res);
}
function back(res)
{
alert(res);
}
</script>
ajax.PHP <? header("Content-Type:gb2312"); echo "how areyou?"; if(isset($_POST["name"])) { echo "hello,".$_POST["name"]; } ?>