How is AJAX used in PHP?

Here is how you can use AJAX in PHP:

  1. 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();
}
  1. Data retrieved using AJAX
<?php
// 连接到数据库 或 执行其他操作
// 查询数据
// 返回数据
echo "Data retrieved from server";
?>
  1. 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.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds