回调函数封装AJAX

115 阅读1分钟
  • 首先我们使用原生AJAX请求网络
//前端代码
    <button onclick="fn()">点击</button>
    <script>
        function fn(){
            var xhr=new XMLHttpRequest()||new ActiveXObject("Microsoft.XMLHTTP");
            xhr.open('GET','/ajax1',true)
            xhr.send()
            xhr.onreadystatechange=function(){
                if(xhr.readyState==4&&xhr.status==200){
                    console.log(xhr.responseText,111)
                }else if(xhr.readyState==4&&xhr.status==404){
                    console.log(xhr.responseText, 22)
                }
            }
        }
    </script>
//后端代码
var router=require('./router.js')//直接封装模块
var request=require('request')
router.get('/ajax1',(req,res)=>{
    res.end('"name":"karen"')
	})

image.png

  • 用回调函数封装AJAX
<script>
        function myfn(url, cb) {
            var xhr = new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP");
            xhr.open("GET", url, true)
            xhr.send()
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    cb(xhr.responseText)
                }
            }
        }

        myfn('/ajax1', (req) => {
            console.log(req)
        })
        myfn('/ajax2', (req) => {
            console.log(req)
        })
    </script>
var router=require('./router.js')//直接封装模块
router.get('/ajax1',(req,res)=>{
    res.end('"name":"karen"')
	})
  router.get('/ajax2',(req,res)=>{
    res.end('"age":18')
	})

image.png

如果不封装AJAX的话,每一次请求一个网址都要写一遍AJAX的代码,比较繁琐,封装之后每次请求网络只需要调函数就行,简化了代码的书写