<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
//--在这里粗心,把var xhr=null;定义在function XMLhttp()里了,哎。。
var xhr=null;
function createXMLhttp()
{
try{
xhr=new XMLHttpRequest();
return xhr;
}catch(e)
{
xhr=new ActiveObject("Micorosoft.XMLHTTP");
return xhr;
}
}
function gettext()
{
var xhr=createXMLhttp();
var parms="i_want_text=yes";//这里是要发送的内容
var url="ajax.php";//对象网页
xhr.open("POST",url,true);//用POST提交。当用POST提交时,我们一般都把要发送的直接嵌入url中
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");//设置HTTP协议头信息
xhr.setRequestHeader("Content-length",parms.length);
xhr.setRequestHeader("Connection","close");
xhr.onreadystatechange=ready;//这里ready不需要(),你也可以这样写function(){ready();}
xhr.send(parms);
}
function ready()
{
//有四个状态,4表示已完全加载,想了解,可以百度readyState
if(xhr.readyState==4)
{
if(xhr.status==200)//200 IS OK
{
var p=xhr.reponseText;//这里是以文本返回
//var p=xhr.responseXML.getElementsByTagName("name");//这里是以XML格式返回
for(i=0;i<p.length;i++)
{
var pa=document.createElement("p");//在网页body中新建一个段
var text=document.createTextNode(p[i].firstChild.nodeValue);//创建文本区结点
pa.appendChild(text);//将文本结点加入pa中
document.getElementById("id1").appendChild(pa);
}
}
else
{
alert("Error with Ajax call!");
}
}
}
</script>
</head>
<body οnlοad="gettext();">
<div id="id1">
</div>
</body>
</html>
上面是请求网页,在请求网页中我们用了三个函数
createXMLhttp()
function gettext()
function ready()
他们就组成了我们对应网页的请求,第一个函数是创建对象,XMLHttpRequest()用于firefox,chorme等浏览器,如果用的是IE,我们则用ActiveObject(“Microsoft.XMLHTTP”),对于第二个函数就是为了得到我们需要的文本,第三个函数,如果我们没有出错,我们可以再其中操作返回的数据。
下面是AJAX.PHP
<?php
/**
* ajax.html
* 2013.4,17
*/
error_reporting(0);
//当请求是responseText,我们用此处理
if ($_POST["i_want_text"]) {
print "返回文本 " . $_POST["i_want_text"];
}
/*当请求是ResponseXML时,我们用此处理
if ($_POST["i_want_xml"]) {
header ("Content-type: text/xml");
print "<student>";
print "<name>";
print "文本 " . $_POST["xml"] ;
print "</name>";
print "<name>";
print "MROU";
print "</name>";
print "</student>";
}
?>