XMLHttpRequest只是一个JavaScript对象,确切的说,是一个构造函数。
它是由客户端(即浏览器)提供的(而不是JavaScript原生的)
它有属性,有方法,需要通过new关键字进行实例化
const xhr = new XMLHttpRequest()
方法
xhr的方法
.open(),准备启动一个AJAX请求
.setRequestHeader(),设置请求头部信息
.send(),发送AJAX请求
.getResponseHeader(),获得响应头部信息
.getAllResponseHeader(),获得一个包含所有头部信息的长字符串
.abort(),取消异步请求
属性
.responseText,包含响应主体返回文本 .responseXML,如果响应的内容类型时text/xml或application/xml,该属性将保存包含着相应数据的XML DOM文档 .status,响应的HTTP状态 .statusText,HTTP状态的说明 .readyState,表示“请求“/”响应“过程的当前活动阶段
Ajax-get请求
const xhr = new XMLHttpRequest() // 1.创建xhr对象 xhr.open("get", "example.php", false) // 2.设置请求方式和地址(?key=value) xhr.onload = function(){ // 3.注册回调函数 document.write(xhr.response); } /// xhr.setRequestHeader("myHeader", "goodHeader") // 自定义请求头信息 xhr.send(null) // 4.发送请求
Ajax-post请求
const xhr = new XMLHttpRequest() // 1.创建xhr对象 xhr.open("post", "example.php", false) // 2.设置请求方式和请求地址 xhr.setRequestHeader(‘Content-Type‘, ‘application/x-www-form-urlencoded‘); // 3.设置请求头 xhr.onload = function(){ // 4.注册回调函数 document.write(xhr.response); } xhr.send(‘key=value‘) // 5.发送请求(传递的数据通过send()方法来发送)
解析
Ajax-get同步请求
const xhr = new XMLHttpRequest() // 1.创建xhr对象 xhr.open("get", "example.php", false) // 2.设置请求方式和地址(?key=value) xhr.setRequestHeader("myHeader", "goodHeader") // 自定义请求头信息 xhr.send(null) // 4.发送请求 // 由于是同步的AJAX请求,因此只有当服务器响应后才会继续执行下面的代码 // 因此xhr.status的值一定不为默认值 if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) { alert(xhr.responseText) } else { alert("Request was unsuccessful: " + xhr.status) }
Ajax-post异步请求
const xhr = new XMLHttpRequest() xhr.onreadystatechange = () => { if (xhr.readystate == 4) { if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) { alert(xhr.responseText) } else { alert("Request was unsuccessful: " + xhr.status) } } } xhr.open("get", "example.php", true) xhr.setRequestHeader(‘Content-Type‘, ‘application/x-www-form-urlencoded‘); xhr.send(‘key=value‘)
end.
参:https://juejin.im/post/5a20b1f1f265da432529179c
原文:https://www.cnblogs.com/wn798/p/12191770.html