Home > Article > Backend Development > 跪求ajax问题
<!DOCUTYPE html><html> <head> <title>聊天窗口</title> <meta http-equiv="Content-type" content="text/html; charset=UTF-8"> </head> <script type="text/javascript"> window.resizeTo(580,650); window.setInterval("getMessage()", 3000); function getXmlHttpObject(){ var xmlHttpRequest; //不同的浏览器获取对象xmlhttprequest对象方法不一样 if(window.ActiveXObject){ xmlHttpRequest =new ActiveXObject("Microsoft.XMLHTTP"); }else{ xmlHttpRequest =new XMLHttpRequest(); } return xmlHttpRequest; } function getMessage() { var myXmlHttpRequest = getXmlHttpObject(); if(myXmlHttpRequest) { var url = "getMessage.php"; var data = "getter=<?php @session_start(); echo $_SESSION['username'];?>&sender=<?php echo $_GET['username'];?>"; myXmlHttpRequest.open("post",url,true); myXmlHttpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded"); myXmlHttpRequest.onreadystatechange=function() { if(myXmlHttpRequest.readyState==4) { if(myXmlHttpRequest.status==200) { //接收 var mes=myXmlHttpRequest.responseXML; window.alert(mes); //这里打印出来老是为null } } } myXmlHttpRequest.send(data); } } function sendMessage() { var myXmlHttpRequest = getXmlHttpObject(); if(myXmlHttpRequest) { var url = "sendMessage.php"; var data = "con=" + $('con').value +"&getter=<?php echo $_GET['username'];?>"+"&sender=<?php @session_start(); echo $_SESSION['username'];?>"; myXmlHttpRequest.open("post",url,true); myXmlHttpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded"); myXmlHttpRequest.onreadystatechange=function() { if(myXmlHttpRequest.readyState==4) { if(myXmlHttpRequest.status==200) { } } } myXmlHttpRequest.send(data); } } function $(id) { return document.getElementById(id); } </script> <body> <center> <h2><span style="color:red;"><?php @session_start(); echo $_SESSION['username'];?></span>跟<span style="color:red;"><?php echo $_GET['username'];?></span>聊天</h2> <textarea name="context" rows="20" cols="70"></textarea><br/> <input style="width:300px" type="text" name="sendcontext" id="con"> <input type="button" name="send" onclick="sendMessage();" value="发送"> </center> </body></html>
<?php include "MessageServer.class.php"; @header( 'Content-Type:text/xml;charset=utf-8'); @header("Cache-Control: no-cache"); $getter = $_POST['getter']; $sender = $_POST['sender']; //调用MessageSerive获取信息 $messageServer = new MessageServer(); $messList = $messageServer->getMessage($getter, $sender); echo $messList; ?>
//接收
var mes=myXmlHttpRequest.responseXML;
if(mes.xml == '') {
alert(myXmlHttpRequest.responseText);
return;
}
window.alert(mes); //这里打印出来老是为null
是数据流,你没有定义输入的内容格式 ,可以是json或数据
if(myXmlHttpRequest.status==200) {
if(myXmlHttpRequest.recvType=="XML")
echo myXmlHttpRequest.responseXML;
}