AJAX代码

AJAX

本质上就是一个封装好的代码

AJAX 的代码怎么写

  const { fail } = require("assert")

const ajax = (obj) => {
    const { method, path, body, successFn, failFn } = obj //析构赋值
    const xhr = new XMLHttpRequest()
    xhr.open(method, path)
    xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                // console.log('请求成功,得到内容为:' + xhr.responseText)
                successFn(xhr)
            } else if (xhr.status >= 400) {
                // console.log('请求失败,状态码为:' + xhr.status)
                failFn(xhr)
            }
        }
    }

    xhr.send(body)
    return {
        abort: () => {
            xhr.abort(); //这里仍然使用了闭包 这里相当于return api 函数外也可以通过这个api来调用函数类的变量
        }
    }

}

关于AJAX的优缺点

优点

  • 1.可以请求任何内容(css data…)
  • 2.不需要刷新页面

缺点

  • 1.代码难记,但可以是用别人的封装
  • 2.不能跨域

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值