封装ajax
// 封装ajax var request = (url, type = "get", data = "", header, async = true) => { console.log(header); var headers = {}; switch (header) { case 1: headers["Content-Type"] = "application/x-www-form-urlencoded";//post提交表单 key1=val1&key2=val2 的方式进行编码 break; case 2: headers["Content-Type"] = "multipart/form-data";//post提交表单 上传文件时使用 break; case 3: headers["Content-Type"] = "text/xml";//用于xml的数据交换格式 break; case 4: headers["Content-Type"] = "application/json";//向后端传递json字符串 data = JSON.stringify(data); break; } var option = { type, url, data, async, // headers, } if (header) {//如果给header传参了 console.log("进来"); option.headers = headers; } console.log(option); return new Promise((resolve, reject) => { $.ajax({ ...option, success (res) { resolve(res); }, error (err) { reject(err) } }) }) }
//简易封装
function getAjax( _methods , url , _data) { return new Promise((resolve,reject) => { let xhr; if(XMLHttpRequest){ xhr = new XMLHttpRequest() }else{ xhr = new ActiveXObject() } let data = _data || null; let methods = _methods || 'get'; xhr.open(methods,url,true) xhr.send(data) xhr.onreadystatechange = () => { if(xhr.readyState == 4){ if(xhr.status == 200){ resolve(JSON.parse(xhr.responseText) ) } else{ reject(JSON.parse(xhr.responseText) ) } } } }) } getAjax('post','http://showme2.myhope365.com/api/cms/category/open/list',{ pageNum:10, pageSize:1 }).then(res => { console.log(res) })