一、XMLHttpRequest是什么?
XMLHttpRequest(XHR)对象用于与服务器交互。通过 XMLHttpRequest 可以在不刷新页面的情况下请求特定 URL,获取数据。这允许网页在不影响用户操作的情况下,更新页面的局部内容。XMLHttpRequest 在 AJAX 编程中被大量使用。
AJAX(Asynchronous JavaScript And XML )是一种使用 XMLHttpRequest 技术构建更复杂,动态的网页的编程实践。
AJAX 允许只更新一个 HTML 页面的部分 DOM,而无须重新加载整个页面。AJAX 还允许异步工作,这意味着当网页的一部分正试图重新加载时,您的代码可以继续运行(相比之下,同步会阻止代码继续运行,直到这部分的网页完成重新加载)。
二、使用XMLHttpRequest
//创建Xhr对象
var xhr = new XMLHttpRequest()
//调用open函数
xhr.open('GET','url地址')
//调用send函数
xhr.send()
//监听onreadystatechange事件
xhr.onreadystatechange = function() {
if(xhr.readystate === 4 && xhr.status === 200) {
console.log(xhr.responseText)
}
}
// post请求
//创建xhr对象
var xhr = new XMLHttpRequest()
//调用open函数
xhr.open('POST','url地址')
//设置Content-Type属性
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
//调用send函数
const data = JSON.stringify({
name:'123'
})
xhr.send(data)
//监听onreadystatechange事件
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
}
三、简单封装
function http(){
var xhr = new XMLHttpRequest()
var baseUrl = '基本地址'
return{
request:(method,url,data,success,err)=>{
xhr.open(method,baseUrl+url)
if (method=='GET'){
xhr.send()
} else {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send(data)
}
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
success(xhr.responseText)
}else{
err()
}
}
}
}
}
//调用
var myHttp = http()
let data = {}
myHttp.request('post','/form',data,function(res){
},function(){
})