基础知识
知识点梳理见图:
自己动手实践案例
案例1: 访问本地文件
<!DOCTYPE html> <html> <body> <div id="demo"> <h1>XMLHttpRequest 对象</h1> <button type="button" onclick="loadDoc()">更改内容</button> </div> <script> function loadDoc() { const myHttp = new XMLHttpRequest(); myHttp.onload = function () { //响应 document.getElementById("demo").innerHTML = this.responseText }; //这里是访问跟文件同一层级下的文件夹下的某个文件 myHttp.open("GET", "./demo/aa.txt",true); myHttp.send(); } </script> </body> </html>
文件的位置:
- 代码效果如下:
文章来源地址https://www.toymoban.com/news/detail-475736.html
- 如果本地测试报错的话,可以看这篇文章: 原生AJAX案例浏览器报错:Cross origin requests are only supported for protocol
案例2:访问服务端数据
<!DOCTYPE html> <html> <body> <div id="demo"> <h1>XMLHttpRequest 对象</h1> <button type="button" onclick="loadDoc()">更改内容</button> </div> <script> function loadDoc() { const myHttp = new XMLHttpRequest(); myHttp.onload = function () { //响应 document.getElementById("demo").innerHTML = this.responseText }; console.log(myHttp.getAllResponseHeaders()) //定义method url myHttp.open("GET", "http://123.207.32.31:5000/test",true); //设置请求头 - 请求头的设置要在open之后,此处 是设置token,必须是 key-val 形式 myHttp.setRequestHeader( "Authorization","eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwibmFtZSI6ImNvZGVyd2h5Iiwicm9sZSI6eyJpZCI6MSwibmFtZSI6Iui2hee6p-euoeeQhuWRmCJ9LCJpYXQiOjE2ODYyMDgxMzMsImV4cCI6MTY4ODgwMDEzM30.Ve6T7h4dGuYmk4Lwch1rlr2pvf11XKfr2F2mxl1kAgp46rvgFxjmUqjhRmq90whydPVYTtrvPnWp1aGY50eVtQcY1olqqwr8ZOngERHIyHgzQxY3zEDLrtcZ5nrNqGeAIutc6kDOgGQFPyOvFOnKKMH7Puwgjydv41XGpEEqNus" ) //定义传输数据 let str = { "name": "dingding", "password": "4569841" } //传递参数 myHttp.send(JSON.stringify(str)); } </script> </body> </html>
- 代码效果如下:
案例3:自己尝试封装一个AJAX
let createAjax = function () { let xhr = null; try { //IE系列浏览器 xhr = new ActiveXObject("microsoft.xmlhttp"); } catch (e1) { try { //非IE浏览器 xhr = new XMLHttpRequest(); } catch (e2) { window.alert("您的浏览器不支持ajax,请更换!"); } } return xhr; }; const ajax = function (config) { debugger; let type = config.type; let dataType = config.dataType; const url = config.url; const data = config.data; const successFn = config.success; const errFn = config.err; const headers = config.headers; if (type === null) { //默认类型为get type = "get"; } if (dataType === null) { dataType = "text"; } //创建XHR对象 const myXHR = createAjax(); myXHR.open(type, url, true); //设置header if (headers !== null) { for (header in headers) { console.log(header); myXHR.setRequestHeader(header); } } //类型 if (type.toLowerCase() == "get") { myXHR.send(null); } else if (type.toLowerCase() === "post") { // myXHR.setRequestHeader("content-type", "application/x-www-form-urlencoded"); myXHR.setRequestHeader("content-type", "application/json"); myXHR.send(data); } //返回数据 myXHR.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { if (dataType.toLowerCase() === "text") { if (successFn !== null) { return successFn(this.responseText); } } if (dataType.toLowerCase() === "xml") { if (successFn !== null) { return successFn(this.responseXML); } } if (dataType.toLowerCase() === "json") { if (successFn !== null) { return successFn(eval("(" + this.responseText + ")")); } } } else { return errFn(this.status); } }; };
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div> <h1 id="demo">XMLHttpRequest 对象</h1> <button type="button" onclick="loadDoc()">更改内容</button> </div> <script src="./03_ajax简单封装.js"></script> <script> function loadDoc() { ajax({ type: "post", url: "http://123.207.32.xxx:5000/login", heasders: { Authorization:"123456123" }, data:JSON.stringify({ "name":'zooey', "password":"123456" }), dataType:'json', success:function(res){ const el = document.querySelector("#demo") el.innerHTML = res.data.id }, err:function(err){ let el = document.querySelector("#demo") el.innerHTML = err } }); } </script> </body> </html>
效果如下:
文章来源:https://www.toymoban.com/news/detail-475736.html
到了这里,关于原生AJAX的学习的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!