使用ts封装一个ajax

练习使用ts 的 接口

interface

/**
 * 使用TS封装一个ajax
 */

 interface Config{
     type:string;

     url:string;

     data?:any; // 可选

     dataType:string;
 }


 function ajax(config:Config){
     let xhr = new XMLHttpRequest();

     xhr.open(config.type,config.url,true);

     xhr.send(config.data);

     xhr.onreadystatechange = function(){
         if(xhr.readyState == 4 && xhr.status == 200){
             if(config.dataType == 'json'){
                 console.log(JSON.parse(xhr.responseText))
             }else{
                 console.log(xhr.responseText)
             }
         }
     }
 }


 //使用

 ajax({
     type:'get',
     url:'localhost:3000',
     data:{name:123},
    dataType:'json'
 })

posted @ 2024-03-12 12:14  打个大大西瓜  阅读(28)  评论(0编辑  收藏  举报