原生ajax 如何解决cors跨域问题
用原生ajax请求进行cors跨域问题 他会显示origin不允许 没有后端支持的情况下怎么写ajax请求头啊。因为可能用到微信小程序,就最好不用第三方库。救救孩子 下面使用promise封装的ajax 要怎么改请求头
#笔试题目#
function ajax(options) { //这个options时传入给ajax的配置参数 return new Promise((resolve, reject) => { //返回一个promise对象 resolve成功是的处理,reject失败时的处理 if (!options.url) { // 需要请求的路径 console.log("请确认你的url路径"); return; } let method = options.method || "GET"; //请求方式如果没有就默认为get let async = options.async || true; //ajax是否异步请求默认位true let xhr = new XMLHttpRequest(); if (method === "GET") { xhr.open(method, options.url + "?" + Math.random(), async); //防止缓存 xhr.send(null); } else if (method === "POST") { xhr.open(method, options.url, async); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(options.data); } // xhr.responseType = options.type || ""; xhr.onreadystatechange = () => { if (xhr.responseText) { //有数据说明相应成功 resolve(xhr.responseText); } }; xhr.onerror = err => { reject(err); }; }).catch(e => {}); }
#笔试题目#