function ajax(method,url,data) { return new Promise((resolve,reject)=> { let xhr = null; try { xhr = new XMLHttpRequest(); }catch(e) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } // get post if(method === 'get' && data) { url += '?' + data; } xhr.open(method,url,true); if(method === 'get') { xhr.send(); }else { xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr.send(data); } xhr.onreadystatechange = function() { if(xhr.readyState == 4) { if(xhr.status == 200) { resolve(xhr.responseText) }else { reject(xhr.status) } } } }) }
用法
ajax('get','01.php',`num=${json}`).then((data)=>{
console.log(data)
})
或者使用
async await
1 async function getData() { 2 3 let data = await ajax('get','data.php',`参数`); 4 5 console.log(data) 6 7 } 8 9 }