在PHP中使用AJAX的方法如下:
- 创建一个包含AJAX请求的JavaScript函数,例如:
functionloadData(){
varxhttp=newXMLHttpRequest();
xhttp.onreadystatechange=function(){
if(this.readyState==4&&this.status==200){
document.getElementById("result").innerHTML=this.responseText;
}
};
xhttp.open("GET","ajax_data.php",true);
xhttp.send();
}
ajax_data.php
:<?php
//连接到数据库或执行其他操作
//查询数据
//返回数据
echo"Dataretrievedfromserver";
?>
<!DOCTYPEhtml>
<html>
<head>
<title>AJAXExample</title>
<script>
functionloadData(){
varxhttp=newXMLHttpRequest();
xhttp.onreadystatechange=function(){
if(this.readyState==4&&this.status==200){
document.getElementById("result").innerHTML=this.responseText;
}
};
xhttp.open("GET","ajax_data.php",true);
xhttp.send();
}
</script>
</head>
<body>
<buttononclick="loadData()">LoadData</button>
<divid="result"></div>
</body>
</html>
这样就可以使用AJAX从服务器端获取数据并更新页面内容。