核心:XMLHttpRequest
AJAX 的使用:
在 js 中有内置的构造函数来创建 ajax 对象
创建 ajax 对象以后,我们就使⽤ ajax 对象的⽅法去发送请求和接受响应
Ajax的一个最大的特点是无需刷新页面便可向服务器传输或读写数据(又称无刷新更新页面),这一特点主要得益于XMLHTTP组件XMLHTTPRequest对象。
XMLHttpRequest 对象属性描述:
XMLHttpRequest 对象方法描述:
open(method,url,async)
规定请求的类型、URL 以及是否异步处理请求。
- method:请求的类型;GET 或 POST
- url:文件在服务器上的位置
- async:true(异步)或 false(同步)
使用XMLHttpRequest()
let page=2 let baseurl="https://jsonplaceholder.typicode.com/posts" function getJSON(url,succ,fail){ const xhr=new XMLHttpRequest() if(!xhr){ if(fail) fail(new Error("No XMLHttpRequest object")) return false } xhr.responseType = "json" xhr.onreadystatechange=function(){ if(xhr.readyState===XMLHttpRequest.DONE){ if(xhr.status===200){ if(succ&&typeof succ==="function") succ(xhr.response) } else { if(fail&&typeof fail==="function") fail(new Error("HTTP status Exception")) } } } xhr.open("GET",url) xhr.send() } function render(page){ getJSON(baseurl+"/"+page, data=>console.log(data), err=>console.log(err.message)) }render(page)