Ajax的Server部分(PHP版)

本文介绍了一个使用PHP和Ajax实现客户端与服务器交互的示例。通过三个不同的触发事件,客户端向服务器发起请求,服务器使用PHP生成XML响应,再由客户端解析并在页面上展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Server端的任务通常是根据Client的请求,进行逻辑操作,并将结果响应返回。这个响应通常为XML格式(因此server端需要使用PHP的DOM创建XML响应)

1.PHP使用DOM创建XML响应,供client端的JS解析然后在页面中显示;(因此需要熟练PHP的DOM API)
其实,PHP生成XML的方法有两种:

使用DOM API;(方法一)
另一种是直接将XML的内容echo出去即可;(方法二)
见示例:
HTML页面(包含三个JS触发函数:onmouseover, onmouseout, onclick; 分别触发自己的函数)
<!doctypehtmlpublic"-//w3c//dtdhtml4.0tRANSITIONAL//en">
<html>
<head>
<title>ServerPHPAjax</title>
<scripttype="text/javascript"src="js.js"></script>
</head>

<body>
<spanonmouseover="PHPechoXML()"onmouseout="PHPDOMXML()">DefaultWords</span>
<divid="show"></div>
divide
<inputtype="text"id="firstNumber"/>by
<inputtype="text"id="secondNumber"/>
<inputtype="button"value="Send"onclick="CSparameter()"/>
<divid="result"></div>
</body>
</html>

JS页面(分别定义三个JS触发函数:PHPechoXML, PHPDOMXML, 以及CSparameter)
其中有XMLHttpRequest对象创建函数,以及各自的Server响应处理函数
///////1.创建XMLHttpRequest对象
varxmlHttp=createXmlHttpRequestObject();

functioncreateXmlHttpRequestObject()
...{
varxmlHttp;

try
...{
//trytocreateXMLHttpRequestobject
xmlHttp=newXMLHttpRequest();
}

catch(e)
...{
//assumeIE6orolder
varXmlHttpVersions=newArray('MSXML2.XMLHTTP.6.0',
'MSXML2.XMLHTTP.5.0',
'MSXML2.XMLHTTP.4.0',
'MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP',
'Microsoft.XMLHTTP');
for(vari=0;i<XmlHttpVersions.length&&!xmlHttp;i++)
...{
try

...{
//trytocreateXMLHttpRequestobject
xmlHttp=newActiveXObject(XmlHttpVersions[i]);
}

catch(e)...{}
}

}

if(!xmlHttp)
alert(
"ErrorcreatingtheXMLHttpRequestobject.");
else
returnxmlHttp;
}



///////2.JavaScript事件响应函数(onmouseover触发)
//
readafilefromtheserver
functionPHPechoXML()
...{
//onlycontinueifxmlHttpisn'tvoid
if(xmlHttp)
...{
//trytoconnecttotheserver
try
...{
//initiatereadingafilefromtheserver
//向Server端的PHPechoXML.php文件发送异步请求
xmlHttp.open("GET","PHPechoXML.php",true);
xmlHttp.onreadystatechange
=handleRequestStateChange;
xmlHttp.send(
null);
}

//displaytheerrorincaseoffailure
catch(e)
...{
alert(
"Can'tconnecttoserver: "+e.toString());
}

}

}


///////3.JavaScript事件响应函数(onmouseout触发)
functionPHPDOMXML()
...{
//onlycontinueifxmlHttpisn'tvoid
if(xmlHttp)
...{
//trytoconnecttotheserver
try
...{
//initiatereadingafilefromtheserver
//向Server端的PHPDOMXML.php文件发送异步请求
xmlHttp.open("GET","PHPDOMXML.php",true);
xmlHttp.onreadystatechange
=handleRequestStateChange;
xmlHttp.send(
null);
}

//displaytheerrorincaseoffailure
catch(e)
...{
alert(
"Can'tconnecttoserver: "+e.toString());
}

}

}


//handlestheresponsereceivedfromtheserver,Server端状态回调函数
functionhandleRequestStateChange()
...{

if(xmlHttp.readyState==4)
...{
//continueonlyifHTTPstatusis"OK"
if(xmlHttp.status==200)
...{
try
...{
//readthemessagefromtheserver
varxmlResponse=xmlHttp.responseXML;

//捕获IE和Opera潜在的错误
if(!xmlResponse||!xmlResponse.documentElement)
...{
throw("InvalidXMLstructure: "+xmlHttp.responseText);
}

//捕获FireFox的潜在错误
varrootNodeName=xmlResponse.documentElement.nodeName;
if(rootNodeName=="parsererror")
...{
throw("InvalidXMLstructure: "+xmlHttp.responseText);
}


//获取Server端响应的XML响应并解析,到网页中显示
//obtaintheXML'sdocumentelement
xmlRoot=xmlResponse.documentElement;
//obtainarrayswithbooktitlesandISBNs
cityArray=xmlRoot.getElementsByTagName("city");
//generateHTMLoutput
varhtml="";
//iteratethroughthearraysandcreateanHTMLstructure
for(vari=0;i<cityArray.length;i++)
html
+=cityArray.item(i).firstChild.data+"<br/>";
//obtainareferencetothe<div>elementonthepage
myDiv=document.getElementById("show");
//displaytheHTMLoutput
myDiv.innerHTML="Serversays:<br/>"+html;
}

catch(e)
...{
//displayerrormessage
alert("Errorreadingtheresponse:"+e.toString());
}

}

else
...{
//displaystatusmessage
alert("Therewasaproblemretrievingthedata: "+
xmlHttp.statusText);
}

}

}




///////4.JavaScript事件响应函数(onclick触发)
functionCSparameter()
...{
//onlycontinueifxmlHttpisn'tvoid
if(xmlHttp)
...{
//trytoconnecttotheserver
try
...{

//获取form中的值
varfirstNumber=document.getElementById("firstNumber").value;
varsecondNumber=document.getElementById("secondNumber").value;

//设置为参数,对Server端的CSparameter.php进行异步请求
varparam="firstNumber="+firstNumber+"&secondNumber="+secondNumber;

//initiatereadingafilefromtheserver
xmlHttp.open("GET","CSparameter.php?"+param,true);
xmlHttp.onreadystatechange
=handleRequestStateChangePara;
xmlHttp.send(
null);
}

//displaytheerrorincaseoffailure
catch(e)
...{
alert(
"Can'tconnecttoserver: "+e.toString());
}

}

}


//Server状态改变回调函数(Server端接受Client端传来的参数经过逻辑计算之后返回XML响应,Client端对XML进行解析,返回更新到页面中)
//
handlestheresponsereceivedfromtheserver
functionhandleRequestStateChangePara()
...{

if(xmlHttp.readyState==4)
...{
//continueonlyifHTTPstatusis"OK"
if(xmlHttp.status==200)
html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值