ajax基础

147 阅读2分钟

ajax

ajax

通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

实现一个ajax请求

  1. 实例化一个XMLHTTPRequest对象
var xhr = new XMLHTTPRequest()
  1. open(method,url,async) 规定请求的类型、URL 以及是否异步处理请求。 method:请求的类型;GET 或 POST url:文件在服务器上的位置 async:true(异步)或 false(同步) send(string) 将请求发送到服务器。 string:仅用于 POST 请求
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();

Async = true

当使用 async=true 时,请规定在响应处于 onreadystatechange 事件中的就绪状态时执行的函数:

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();

Async = false

如需使用 async=false,请将 open() 方法中的第三个参数改为 false: xmlhttp.open("GET","test1.txt",false); 我们不推荐使用 async=false,但是对于一些小型的请求,也是可以的 请记住,JavaScript 会等到服务器响应就绪才继续执行。如果服务器繁忙或缓慢,应用程序会挂起或停止。 注释:当您使用 async=false 时,请不要编写 onreadystatechange 函数 - 把代码放到 send() 语句后面即可:

xmlhttp.open("GET","test1.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

ajax请求githubhttps://api.github.com/users

html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <button id="btn">请求github</button>
    <div id="users">

    </div>
    <script>
        var btn = document.getElementById("btn")
        btn.addEventListener("click",loadusers);
        function loadusers(){
            var xhr =new XMLHttpRequest();
            xhr.open("GET","https://api.github.com/users",true);
            xhr.onload = function(){
                var users = JSON.parse(this.responseText);
                console.log(users)
                var out = '';
                for(var i in users){
                    out+=`
                    <div class="user">
                        <ul>
                            <li>${users[i].id}</li>
                            <li>${users[i].login}</li>
                        </ul>
                    </div>
                    `
                }
                console.log(out);
                document.getElementById("users").innerHTML=out;
            }
            xhr.send();
        }
    </script>
</body>
</html>

w3cschool