4-1.html如下:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>使用Ajax技术载入文档</title>
</head>
<body>
<script type="text/javascript">
function Ajax(){ //定义一个函数来异步获取信息
var xmlHttpReq;
xmlHttpReq = new XMLHttpRequest(); //实例化一个XMLHttpRequest对象
if (xmlHttpReq != null){ //如果对象实例化成功
xmlHttpReq.open("get","4-1.php"); //设置异步请求的方式和请求的URL
xmlHttpReq.send(null); //用send方法发送请求
xmlHttpReq.onreadystatechange = RequestCallBack;}//设置回调函数
function RequestCallBack(){ //一旦readyState值改变,将调用这个函数
if(xmlHttpReq.readyState == 4 && xmlHttpReq.status==200){ //如果浏览器处理完毕并且没有出错
document.getElementById("target").innerHTML = xmlHttpReq.responseText;}//将服务器返回的内容载入到#target元素中
}}
</script>
<input type="button" value="Ajax载入" onclick="Ajax();"/>
<div id="target"></div>
</body>
</html>
4-1.php代码如下:
<?php
echo '<b>Hello Ajax!</b>'.date("Y年m月d日");
?>
点击按钮后出来的效果是
Hello Ajax!'.date("Y年m月d日"); ?>
理想效果应该是加载出具体的年月日
Hello Ajax!2015年10月25日