AJAX - 燕過留毛筆記 super easy

順炸天發表於2020-12-27

ref: https://www.runoob.com/ajax/ajax-examples.html

簡單來講:使用者操作觸發js函式,函式裡有XMLHttpRequest物件給伺服器端傳送請求,獲得響應修改部分html內容的過程。

<!DOCTYPE html>
<html>
    <head>
        <title>ajax text</title>
    </head>

    <body>
        <div id="a">

        </div>
        <button onclick="ajaxText()" type="button">get</button>
        <script type="text/javascript">
            function ajaxText() {
                var ajaxRequest = new XMLHttpRequest();
                ajaxRequest.onreadystatechange = function() {
                    if (ajaxrequest.readyState == 4 && ajaxrequest.status == 200)
                        document.getElementById("a").innerHTML = ajaxRequest.responseText;
                }
                ajaxRequest.open("GET", "./contend.txt", true);
                ajaxRequest.send();
            }
        </script>
    </body>
</html>

1.var ajaxRequest = new XMLHttpRequest();

2. ajaxRequest.onreadystatechange = function() {
                    if (ajaxrequest.readyState == 4 && ajaxrequest.status == 200)
                        document.getElementById("a").innerHTML = ajaxRequest.responseText;
                }
3. ajaxRequest.open("GET", "./contend.txt", true);
4. ajaxRequest.send();

基本順序不能改

返回的響應內容可以有其他形式

相關文章