回调函数
<script> function $ajax({ success }){ var res = 'hello world' success(res) } $ajax({ success:res=>{ console.log(res) } }) </script>
封装ajax
var hot = `http://47.108.197.28:3000/top/playlist?order=hot`function $ajax(url,success){ var xhr = new XMLHttpRequest(); xhr.open("get",url,true); xhr.send(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status==200){ var res = JSON.parse(xhr.responseText); success(res) } }}
调用
$ajax(url,res=>{ console.log(res) })
函数的参数作为对象
var url = 'http://47.108.197.28:3000/banner'function $ajax({ url, success}){ var xhr = new XMLHttpRequest(); xhr.open('get',url,true); xhr.send() xhr.onreadystatechange = function(){ if(xhr.readyState === 4&&xhr.status>=200&&xhr.status<300){ var res = JSON.parse(xhr.responseText) success(res) } }}
调用
<script src="../lib/ajax.js"></script> <script> var url = 'http://47.108.197.28:3000/banner' $ajax({ url, success:res=>{ console.log(res) } }) </script>