首页 > Web开发 > 详细

ES6系列---【利用解构赋值实现ajax封装】

时间:2021-04-13 23:18:13      阅读:19      评论:0      收藏:0      [点我收藏+]

将封装函数保存为外部js, 需要时引用:

  // 利用解构赋值实现ajax封装函数。可灵活使用解构赋值的默认值,这样调用函数时只需要传递必要的参数即可
  function sendAjax({type="get",url,data=null,dataType="json",timeOut="5000"},callback) {
    $.ajax({
      type: type, //请求的方法 get post
      url: url,  //请求的地址
      data: data, // 请求时发送的数据
      dataType: dataType, //期望返回的数据类型
      // ajax成功后的回调函数
      success: function (response) {
        // console.log(respnse);
        callback(response)
      },
      // 失败时的回调函数
      error: function (err) {
        console.log(err);
      }
    });
  }
<script src="./sendAjax.js"></script>
<script>
sendAjax({type:"post",url:"http://api.shenzhou888.com.cn/v2/ecapi.banner.list"},function(data){
    // 渲染页面代码
    console.log( data );
  });
</script>

ES6系列---【利用解构赋值实现ajax封装】

原文:https://www.cnblogs.com/chenhaiyun/p/14655112.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!