How is AJAX used in PHP?
Here is how you can use AJAX in PHP:
- Create a JavaScript function that includes AJAX requests, for example:
function loadData() {
var xhttp = new XMLHttpRequest();
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();
}
- Data retrieved using AJAX
<?php
// 连接到数据库 或 执行其他操作
// 查询数据
// 返回数据
echo "Data retrieved from server";
?>
- Call a JavaScript function in an HTML file and display the result.
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<script>
function loadData() {
var xhttp = new XMLHttpRequest();
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>
<button onclick="loadData()">Load Data</button>
<div id="result"></div>
</body>
</html>
This allows you to use AJAX to fetch data from the server and update the content on the page.