promise封装 原生ajax,$.ajax(),以及fetch

本文介绍如何使用Promise封装原生AJAX实现GET请求,并对比jQuery的$.ajax方法。此外,还探讨了Fetch API的使用方法及其特点,如支持CORS但不支持JSONP。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

promise封装 原生ajax

get方式

function fetch(url){
    return new Promise((res,rej)=>{
        let xhr=new XMLHttpRequest();
        xhr.open('GET',url);
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4&&xhr.status==200){
                res(xhr.responseText)
            }else{
                rej(xhr)
            }
        }
        xhr.send()
        
    })
    
}

调用

fetch(url).then((val)=>{console.log(val)},(err)=>{console.log(err)})
.catch((err)=>{console.log(err)})

$(ajax)

    $.ajax({
           type : "get",              
           url : "test.html",
           async : "true",      // 默认的,可不写
           success : function(data){
                console.log(typeof data);     // 自动转格式
                $(".wrap").html(data);
           }
      });

fetch()方法

在这里插入代码片

> Fetch API提供了一个fetch()方法,它被定义在BOM的window对象中,你可以用它来发起对远程资源的请求。 该方法返回的是一个Promise对象,让你能够对请求的返回结果进行检索。

fetch请求数据

fetch(url, {
  // get 请求可以省略不写 默认的是GET 
  method: 'get'
})
  .then(function(data) {
  return data.text();
}).then(function(data) {
  console.log(data)
});

fetch只支持跨域CORS 不支持JSONP跨越

<script>
    //fetch发送数据
    //支持CORS跨域,没有办法接受jsonp数据
    function getData() {
        //支持 cors跨域url地址'http://api.yytianqi.com/air?city=CH010100&key=2c5br4sgmguremgg'
        //https://api.douban.com/v2/book/1220562?callback=func
       return fetch('http://localhost:3001/getdata')
            .then(function (response) {
                console.log(response);
                //promise对象返回
                return response.json();
            })
    }
    getData().then(function (data) {
        console.log(data);
    })
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值