<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>封裝屬於本身的AJAX類庫</title> </head> <body> <script> //自執行函數 ~function(){ class ajaxClass{ //=>AJAX四步操做:send ajax init(){ //這裏的this就是實例example let xhr = new XMLHttpRequest(); xhr.onreadystatechange = ()=>{ if(xhr.readyState===4&&/^(2|3)\d{2}$/.test(xhr.status)){ let result = xhr.responseText; //dataType的處理 try { switch (this.dataType.toUpperCase()){ case 'TEXT': case 'HTML': break; case 'JSON': result = JSON.parse(result); break; case 'XML': result = xhr.responseXML; } }catch (e){ console.log(e.message); } this.success(result); } } //=>data的處理 if(this.data !==null){ this.formatData(); if(this.isGET){ //若是是get請求 this.url += this.querySymbol()+this.data; this.data = null; } } //=>cache的處理 this.isGET?this.cacheFn():null; xhr.open(this.method,this.url,this.async); xhr.send(this.data); } //把傳遞的對象格式data轉換爲字符串格式類型 formatData(){ //this指向當前實例example //檢測this.data是不是一個對象 if({}.toString.call(this.data)==='[object Object]'){ let obj = this.data, str = ``; for(let key in obj){ str += `${key}=${obj[key]}&`; } str = str.replace(/&$/,'');//把末尾的&進行替換 this.data = str; } } cacheFn(){ //this指向當前實例example !this.cache ?this.url +=`${this.querySymbol}_=${Math.random()}`:null; } //符號查詢 querySymbol(){ //this孩紙指向當前實例example return this.url.indexOf('?')>-1?'&':'?'; } } //=>參數初始化 init parameters window.ajax = function ({ url=null, method='GET', type=null, data=null, dataType='JSON', cache=true, async=true, success=null }={}) { let example = new ajaxClass();//example就是ajaxClass的實例 /*['url','method','data','dataType','cache','async','success'].forEach((item)=>{ if(item==='method'){ _this.method = type===null?method:type; return; }if(item === 'success'){ _this.success = typeof success === 'function'?success:new Function(); return; } _this[item] = eval(item); })*/ example.url = url; example.method = type===null?method:type; example.data = data; example.dataType = dataType; example.async = async; example.success = typeof success === 'function'?success:new Function(); example.isGET = /^(GET|DELETE|HEAD)$/i.test(example.method); example.init();//執行init方法 return example; }; }(); ajax({ url:'product.json', method:'post', cache:false, data:{ name:'zhangsan', age:18 }, dataType:'text', success: result=>{ console.log(result); } }) </script> </body> </html>