在页面底部加上下面代码即可:
<script type="text/javascript">
var connector = (function(){
var connector = null;
if(window.XMLHttpRequest){
connector = new XMLHttpRequest();
}else if(window.ActiveXObject){
connector = new ActiveXObject('Microsoft.XMLHTTP');
}
return connector;
})();
var innerText = document.body.innerText ? 'innerText' : 'textContent';
var handler = function(response){
document.getElementById('test').getElementsByTagName('pre')[0][innerText] = response;
}
connector.onreadystatechange = (function(callback){
return function(){
if(connector.readyState == 4){//这里connector.status == 200都省了。
callback.call(connector,connector.responseText);
}
}
})(handler);
connector.open('GET',location.href,true);//发送到本页面
connector.send();
</script>
例如:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<div id="test">
<pre>
休息休息
</pre>
</div>
<script type="text/javascript" src="ajax.js"></script>
<script type="text/javascript">
var connector = (function(){
var connector = null;
if(window.XMLHttpRequest){
connector = new XMLHttpRequest();
}else if(window.ActiveXObject){
connector = new ActiveXObject('Microsoft.XMLHTTP');
}
return connector;
})();
var innerText = document.body.innerText ? 'innerText' : 'textContent';
var handler = function(response){
document.getElementById('test').getElementsByTagName('pre')[0][innerText] = response;
}
connector.onreadystatechange = (function(callback){
return function(){
if(connector.readyState == 4){//这里connector.status == 200都省了。
callback.call(connector,connector.responseText);
}
}
})(handler);
connector.open('GET',location.href,true);//发送到本页面
connector.send();
</script>
</body>
</html>
再来一个跨页面的例子:
<script language="javascript">
var xmlhttp;
if (window.XMLHttpRequest) { //for IE7+, Firefox, Chrome, Opera, Safari -OK
xmlhttp = new XMLHttpRequest();
}
else { // for IE6, IE5 -OK
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//document.getElementById("test").innerHTML = xmlhttp.responseText;
document.write(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "laiyuan.html", true);
xmlhttp.send();
</script>
注释掉的那行是可以显示在本面指定ID的元素里