原生js实现ajax调用接口功能

//1 封装ajax

function ajax(option){
       //创建异步对象
    var xhr = null;
    if (window.XMLHttpRequest) {
       xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
       xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
       //如果是get并且有数据
       if(option.type=='get'&&option.data){
            option.url=option.url+'?'+option.data;
       }
       //设置请求行
       xhr.open(option.type,option.url);
       //设置请求头(post有数据发送才需要设置请求头)
       //判断是否有数据发送
       if(option.type=='post'&&option.data){
             xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
       }
       //注册回调函数
       xhr.onreadystatechange = function(){
             if(xhr.readyState==4&&xhr.status==200){
                 //接收返回的数据类型
                 var type = xhr.getResponseHeader('Content-Type');
                 //json格式
                 if(type.indexOf('json')!=-1){
                      option.callback(JSON.parse(xhr.responseText));
                 }
                 //xml格式
                 else if(type.indexOf('xml')!=-1){
                      option.callback(xhr.responseXML);
                 }
                 //普通格式
                 else{
                      option.callback(xhr.responseText);
                 }
             }
       }
       //发送请求主体
       //判断不同的请求类型
       xhr.send(option.type=='post'?option.data:null);
  }

//2 调用实例 

// 获取热词
  function getHotWord () {
    ajax({
      type: 'get',
      url: baseUrl + '/api/v1/search/hotword',
      data: null,
      callback: function (res){
        var dat = [];
        if (res.status == 1) {
          console.log(res.data);
          var hotword=res.data&&res.data.words[0];
          if(hotword){
            $input.setAttribute("data-hotword",hotword);
            if(!$input.value){
              let hword = res.data.words[0];
              $input.value = hword;
              let classAtr = $input.getAttribute("class");
              let newClass = classAtr.concat(" hot-keyword");
              $input.setAttribute("class",newClass);
            }
          }
        }
      }
    })
  }

 //3调用方法

    getHotWord ();
 

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值