回调函数

  1. <script>
  2. function $ajax({
  3. success
  4. }){
  5. var res = 'hello world'
  6. success(res)
  7. }
  8. $ajax({
  9. success:res=>{
  10. console.log(res)
  11. }
  12. })
  13. </script>

封装ajax

  1. var hot = `http://47.108.197.28:3000/top/playlist?order=hot`
  2. function $ajax(url,success){
  3. var xhr = new XMLHttpRequest();
  4. xhr.open("get",url,true);
  5. xhr.send();
  6. xhr.onreadystatechange = function(){
  7. if(xhr.readyState == 4 && xhr.status==200){
  8. var res = JSON.parse(xhr.responseText);
  9. success(res)
  10. }
  11. }
  12. }

调用

  1. $ajax(url,res=>{
  2. console.log(res)
  3. })

函数的参数作为对象

  1. var url = 'http://47.108.197.28:3000/banner'
  2. function $ajax({
  3. url,
  4. success
  5. }){
  6. var xhr = new XMLHttpRequest();
  7. xhr.open('get',url,true);
  8. xhr.send()
  9. xhr.onreadystatechange = function(){
  10. if(xhr.readyState === 4&&xhr.status>=200&&xhr.status<300){
  11. var res = JSON.parse(xhr.responseText)
  12. success(res)
  13. }
  14. }
  15. }

调用

  1. <script src="../lib/ajax.js"></script>
  2. <script>
  3. var url = 'http://47.108.197.28:3000/banner'
  4. $ajax({
  5. url,
  6. success:res=>{
  7. console.log(res)
  8. }
  9. })
  10. </script>